Tuesday, October 18, 2016

Handling multiple Foreign Keys to the same database table in Entity Framework Code First

I recently encountered a requirement while working with Entity Framework Code First that required mapping more than 2 foreign keys to the same database table.

The convention for Entity Framework Code First, by default, does not make this easy simply by defining [ForeignKey] Data Annotations.

Fortunately, a quick search turned up this Stack Overflow thread: http://stackoverflow.com/questions/5559043/entity-framework-code-first-two-foreign-keys-from-same-table

This thread ultimately resulted in 2 possible solutions to this problem.

The first solution required the usage of the FluentAPI for Entity Framework Code First by relying on the OnModelCreating event in the DbContext class:

The second solution required the use of the [InverseProperty] Data Annotation instead:

No comments:

Post a Comment