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.
The following code will automatically generate the many to many relationship between the “Consultant” and “Project” entity classes:
And this will lead to the following database schema:
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:
And don’t forget to add the virtual ProjectConsultants property on the Project and Consultant class:
After running this will now lead to this schema:
Did you like this article and would you like to help us win an award? Please vote! ITQ has been nominated as Service Supplier of the Year by Computable Magazine, but we need your help to take the award to Wijk aan Zee.
Voting takes about 5 minutes and can be done through this link.