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.
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
.HasForegnKey(e => e.CounterpartyId)