MapKey vs HasForeignKey Difference - Fluent Api

ef-code-first entity-framework entity-relationship

Question

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);
1
54
3/24/2013 6:43:47 AM

Accepted Answer

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:

85
5/23/2017 12:26:22 PM


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