Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapKey vs HasForeignKey Difference - Fluent Api

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); 
like image 666
parliament Avatar asked Mar 24 '13 06:03

parliament


People also ask

What is fluent API used for?

Fluent API is an advanced way of specifying model configuration that covers everything that data annotations can do in addition to some more advanced configuration not possible with data annotations.


1 Answers

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:

  • http://www.ladislavmrnka.com/2011/05/foreign-key-vs-independent-associations-in-ef-4/
  • What are Independent Associations and Foreign Key Associations?
  • Code First: Independent associations vs. Foreign key associations?
like image 123
Slauma Avatar answered Sep 20 '22 03:09

Slauma