entity-frameworkdatabase-firstef-database-first

EF Database first many to many with additional field


Now this is probably a silly issue but it's giving me quite a headache.

What I'm trying to accomplish is for EF to generate 2 objects with M-M relationship. Material and Product. A Product has many materials, and one material can be found in multiple products. The trick is that materials can be measured, for example, with kg and I need to know how much kg does one material hold in the product it's in. Note: Materials can exist without product, product can not exist without material.

This is the initial design I've come up with but it obviously doesn't work.

[Material]  [Product]    [MaterialInProduct]
ID  *PK     ID  *PK      ProductID  *FK              __together these two fields are primary key          
Code        Code         MaterialID *FK              for this table
Name        Name         QuantityOfMaterialInProduct 
Price       Quantity
Unit        Unit
Quantity

So my question would be, how to properly add that QuantityOfMaterialInProduct field, since without it DBContext tool generates everything properly.


Solution

  • Instead of having EF create the many-to-many association, define the MaterialInProduct entity yourself. You can map it to have a composite key made from the ProductId and MaterialId (with associated navigation properties). Doing it this way, you can easily add any additional fields.

    You can find documentation on custom mapping here