Relationships in Entity Framework Code First

In this article I will describe a common mapping problem with relationships in Entity Framework Code First. I once had this problem as well and got the answer from StackOverflow (if interested, see my question here).

Consider the following models:

And the following (psuedo)code to save a ClassA:

The code above is called an independent association. A disadvantage of this approach is that each association has its own state, and it can’t be in the Modified state. In my example the relation will not be saved correctly, but there are various other cases where you will end up with duplicates of an entity of ClassB.

The opposite is a foreign key association. In this type of mapping the models have integers that act as foreign keys. You don’t need to handle with object states and data-binding problems, but from an object-oriented view it’s wrong since you can’t access the foreign objects through a reference.

The solution is to use a combination of both:

Entity Framework will automatically detect that BId is a foreign key for navigation property B. Now you can change the Save function to this:

You can now use the advantages of a foreign key association (checking the FK for null, use model-binding, etc.) and an independent association (directly access referenced properties).

Changing from independent to foreign key association

If your database is already generated (i.e. the foreign key already exists with a different name) and you want to change your models to a foreign key association you can solve this by using a custom mapping configuration, for example:


Leave a Reply

Your email address will not be published. Required fields are marked *