One of the features of Code First is the automatic creation of join tables for many to many relationships, Entity Framework will manage these join tables internally and hidden. So it’s a table without an Entity class in your model.

image_27

The following code will automatically generate the many to many relationship between the “Consultant” and “Project” entity classes:

image_28

image_29

And this will lead to the following database schema:

clip_image002

In some scenarios it may be required to add additional fields to the join table. For example in this scenario we have a property “MaxHours” on a project, which probable contains the maximum number of hours it may take, but in this model it is not possible to store the maximum hours a consultant may spent on a project. This will require an additional field “MaxHours” on the ProjectConsultants table.

It is not possible to have additional properties on the auto-generated hidden tables in EF, so to create this will require a different approach. Simply said we still have to do it ourselves by creating an Entity class for ProjectConsultants with 2 foreign keys:

image_30

image_31

And don’t forget to add the virtual ProjectConsultants property on the Project and Consultant class:

image_32

After running this will now lead to this schema:

clip_image004

Paul Zonneveld

Author Paul Zonneveld

More posts by Paul Zonneveld
13 June 2012

Leave a Reply