[英]If I have a non standard Foreign Key name do I need to manually setup both sides of a relationship?
I am working on a Database First project and I am using a EntityTypeConfiguration
class to set up Fluent definations of my models (Used the "Reverse Engineer Code First" tool to get the initial classes). 我正在开发一个Database First项目,我正在使用
EntityTypeConfiguration
类来设置我的模型的Fluent定义(使用“Reverse Engineer Code First”工具来获取初始类)。
In one set of my classes I have a non standard key n that associates two objects in a one to many relationship. 在我的一组课程中,我有一个非标准键n,它将两个对象关联成一对多的关系。 Here is a example set of classes.
这是一组示例。
class Foo
{
public int FooId {get; set;}
public string SomeData {get; set;}
public virtual ICollection<Bar> Bars {get; set;}
}
class Bar
{
public int BarId {get; set;}
public int ThisIntPointsToFooId {get; set;}
public virtual Foo Foo {get; set;}
}
When I create EntityTypeConfiguration<Foo>
and EntityTypeConfiguration<Bar>
do I need to define the relationship from both sides or can I do it from just one side and the other will pick it up? 当我创建
EntityTypeConfiguration<Foo>
和EntityTypeConfiguration<Bar>
,我是否需要从两侧定义关系,或者我可以从一侧进行,另一侧是否可以选择它?
class FooMap : EntityTypeConfiguration<Foo>
{
//(Snip other members)
this.HasMany(t => t.Bars).WithRequired(t => t.Foo).HasForeignKey(t => t.ThisIntPointsToFooId);
}
class BarMap : EntityTypeConfiguration<Bar>
{
//(Snip other members)
this.HasRequired(t => t.Foo).WithMany(t => t.Bars).HasForeignKey(t => t.ThisIntPointsToFooId);
}
One mapping is enough - and actually better in my opinion. 一个映射就足够了 - 在我看来实际上更好。 If you want to change something - like making the FK nullable and the relationship optional (
HasOptional
/ WithOptional
) or adding WillCascadeOnDelete(false)
to the relationship - you don't have to care about two mappings but only change one place. 如果你想改变一些东西 - 比如使FK可以为空并且关系可选(
HasOptional
/ WithOptional
)或将WillCascadeOnDelete(false)
添加到关系中 - 你不必关心两个映射但只改变一个地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.