0

I have read many about how to configure many to many realtionships with EF Code First and fluent configuration. But I couldn't understand why I should create an extra entity for the junction table. Lets assume that I have the following entities:

Department
----------
Id
Name

Material
----------
Id
Name

Now I want to keep records of materials for each department. So I need

DepartmentMaterial
-------------------
DepartmentId
MaterialId
Quantity

What I have read so far I need 3 entities: Department, Material and DepartmentMaterial. So actually I am mapping each table to a corresponding entity which was not I intended to do when I started to learn about DDD. I assumed that EF is going to map that junction table automatically and also queries about material quantities can be done over Department.

Hence, is it possible in EF Code First to configure fluently such a relation without an extra entity?

Kadir.K
  • 366
  • 4
  • 17

1 Answers1

1

The junction table can stay out of the conceptual model (class model) if it's only got two foreign keys (DepartmentId, MaterialId). You want to record some data about the association. That's OK, the quantity belongs there. A department has quantity x of material y. Saying that a department has a quantity is meaningless.

This is not against DDD principles. The association class is a first-class citizen in the class model. It could even have its own behavior (like limiting quantities for certain department/material combinations).

This means that your model will not contain a many-to-many association but Department 1-n DepartmentMaterial n-1 Material. And you'll have to query materials of departments through the junction table. This is a very common situation. I hardly ever see pure junction tables in real life. They're collector's items.

Example query:

var query = from d in db.Departments
            from dm in d.DepartmentMaterials
            select new { Department = d, Materials = dm.Select(x => x.Material)};
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291