MapKey vs HasForeignKey差异 - 流利的Api [英] MapKey vs HasForeignKey Difference - Fluent Api
问题描述
实际上有什么区别:
this.HasRequired(a => a.Something)
.WithMany()
.Map(a => a.MapKey("SomethingId"));
和
this.HasRequired(a => a.Something)
.WithMany()
.HasForeignKey(a => a.SomethingId);
推荐答案
两个映射都将创建完全相同的数据库模式,不可空的外键 SomethingId
和两个相关表之间的参照约束。
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.
第一个映射为 MapKey
当您不想将外键作为模型类中的属性时使用。在这种情况下,关联的类型称为独立关联 。当外键是模型中的属性时,您将应用第二个映射 HasForeignKey
。这种类型称为外键协会。
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/
- 什么是独立协会和外国关键协会?
- 代码第一:独立为社会与外国关键协会?
- 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?
这篇关于MapKey vs HasForeignKey差异 - 流利的Api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!