56

What is actually the difference between:

this.HasRequired(a => a.Something)
    .WithMany()
    .Map(a => a.MapKey("SomethingId"));

and

this.HasRequired(a => a.Something)
    .WithMany()
    .HasForeignKey(a => a.SomethingId);
parliament
  • 21,544
  • 38
  • 148
  • 238

1 Answers1

88

Both mappings will create exactly the same database schema with a non-nullable foreign key SomethingId and a referential constraint between the two related tables.

The first mapping with MapKey is used when you don't want to have the foreign key as a property in your model class. The type of association in this case is called Independent Association. You would apply the second mapping with HasForeignKey when the foreign key is a property in the model. This type is called Foreign Key Association.

In many scenarios it is easier to work with Foreign Key Associations, but many people consider it as less clean to have a relational artifact (a foreign key) in the object world and prefer Independent Associations therefore.

Here are some references about the two types of associations and their Pros and Cons:

Community
  • 1
  • 1
Slauma
  • 175,098
  • 59
  • 401
  • 420
  • 1
    "Many people think that an object-relational mapping tool is suppose to solve the object-relational impedance mismatch rather than forcing or even encouraging you to make your object model look like it was designed specifically around how the data is persisted". There, I fixed it for you. – Derek Greer Mar 24 '17 at 22:29
  • My thoughts exactly! If there's a foreign key in the database then either the distinction between MapKey and HasForeignKey is practically meaningless, or you've made a poor design decision. IMNSHO. – EGP Jan 13 '20 at 14:52