Search code examples
nhibernateentity-frameworkormmany-to-manydomain-model

ORM and many-to-many relationships


This is more or less a general question and not about any specific ORM or language in particular: this question comes up regardless of your ORM preference.

When mapping a many-to-many relationship it is possible to obscure the intermediary table or to make the intermediary table a part of your model. In the case that the intermediary table has valuable data beyond the relationship, how do you handle the mapping?

Consider the following tables:

CaseWorker (id, first_name, last_name)
CaseWorkerCases (case_worker_id, case_id, date_opened, date_closed)
Case (id, client_id, field_a, field_b)

As a programmer I would really rather be able to do:

CaseWorker.Cases

than

CaseWorker.CaseWorkerCases.Cases

On the one hand, the table CaseWorkerCases contains useful data and hiding the intermediary table makes accessing that data less than convenient. On the other, having to navigate through the intermediary table makes the common task of accessing Cases seem awkward.

I supose one solution could be to expose the intermediate table in the model and then give the CaseWork object a wrapper property could work. Something like:

public IEnumerable<Case> Cases
{
    get{return (from caseWorkerCase in this.CaseWorkerCases
                select caseWorkerCase.Case);}
}

But that also seems wrong.


Solution

  • I don't think your workaround is wrong. The complexities of these models have to be coded somewhere.

    I have a blog post about this exact topic: Many-to-many relationships with properties