Question

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.

Was it helpful?

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

OTHER TIPS

I regard many-to-many mappings as just a notational abbreviation for two one-to-many mappings with the intermediate table, as you call it, enabling simplification of the relationships. It only works where the relationships do not have attributes of their own. However, as understanding of the particular domain improves, I usually find that many-to-many mappings usually need to be broken down to allow attributes to be attached. So my usual approach these days is to always simply use one-to-many mappings to start with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top