Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
849 views
in Technique[技术] by (71.8m points)

entity framework - 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...