0

我正在做一个 Database First 项目,我正在使用一个EntityTypeConfiguration类来设置我的模型的 Fluent 定义(使用“逆向工程师代码优先”工具来获取初始类)。

在我的一组类中,我有一个非标准键 n,它以一对多的关系关联两个对象。这是一组示例类。

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;}
}

当我创建时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);
}
4

1 回答 1

2

一个映射就足够了——在我看来实际上更好。如果你想改变一些东西——比如使 FK 可以为空并且关系是可选的(HasOptional/ WithOptional)或者添加WillCascadeOnDelete(false)到关系中——你不必关心两个映射,而只改变一个地方。

于 2014-03-12T23:42:13.563 回答