O'Reilly logo

Programming Entity Framework: Code First by Rowan Miller, Julia Lerman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mapping Relationships

So far you have seen how to control the mapping of classes and their primitive properties; the final piece is to look at how relationships are mapped. This includes controlling the name of foreign key columns and the name of the join table in many-to-many relationships. Chapter 4 covered a wide variety of conventions and configurations for relationships. Now that you are more familiar with mappings, this section will provide you with additional ways to control particular details of how those relationships are mapped.

Controlling Foreign Keys Included in Your Class

You’ve seen that a relationship is created by adding navigation properties between two classes. You’ve also seen that you can optionally include a foreign key property in the dependent class. By default, Code First will use the property name as the name for the column. You saw this back in Chapter 4, when you added the DestinationId to the Lodging class. Code First added a DestinationId column to your database and configured it as a foreign key.

Changing the column name for a foreign key property is exactly the same as changing the column name for any other primitive property. Changing the column name of a foreign key property has no impact on Code First’s ability to detect that it is a foreign key. Foreign key detection only considers the property name and not the name of the column it is mapped to.

Let’s say you want to change the column name to be destination_id. You can apply the Column annotation ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required