In Entity Framework code first, to map a navigation property do I also need to map the foreign key column

entity-framework-6

Question

Say I have a Trade object which has a foreign key to a Counterparty object. I want to have a navigation property of type Counterparty in my Trade object- do I also need to have the foreign key column (CounterpartyId) in my Trade object? My experimentation seems to indicate that I do. I tried adding [ForeignKey("CounterpartyId"] on the navigation but it doesn't work without also having the CounterpartyId column.

1
1
7/9/2017 10:12:26 AM

Accepted Answer

No, the explicit FK property is not mandatory. Just if you skip it, by convention EF assumes "Counterparty_Id" shadow property and column name in the corresponding database table.

In this case there is no way to configure the shadow property/column name with data annotations, so if you want to do that you'll need fluent configuration with MapKey (as opposed to HasForeignKey when you do have an explicit property):

modelBuilder.Entity<Trade>()
    .HasRequired(e => e.Counterparty) // or HasOptional if you want nullable column
    .WithMany() // or WithMany(e => e.Trades) if you have inverse collection navigation property
    .Map(m => m.MapKey("CounterpartyId"));

Note that the fluent configuration must reflect exactly your model navigation / FK properties. For instance, you later on you decide to add ConterpartyId property to your Trade object, you should replace the Map with

.HasForegnKey(e => e.CounterpartyId)
3
7/9/2017 10:41:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow