如何在代码第一个实体框架中建立三重关系

时间:2015-07-13 13:59:24

标签: entity-framework entity-framework-5

如何在EF中建立三重关系? 我打算做的是这样的事情:

Table Foo: (ID INT TEXT VARCHAR)
Table Coo: (ID INT TEXT VARCHAR)
Table Boo: (ID INT TEXT VARCHAR)
Table FooCooBoo: (FKFoo INT FKCoo INT FKBoo INT)

我希望使用下面的代码可以实现:

public class Foo
{
    public int Id { get; set; }
    public string Text { get; set; }

    public virtual ICollection<Boo> Boos { get; set; }
    public virtual ICollection<Coo> Coos { get; set; }
}

public class Boo
{
    public int Id { get; set; }
    public string Text { get; set; }

    public virtual ICollection<Foo> Foos { get; set; }
    public virtual ICollection<Coo> Coos { get; set; }
}

public class Coo
{
    public int Id { get; set; }
    public string Text { get; set; }

    public virtual ICollection<Boo> Boos { get; set; }
    public virtual ICollection<Foo> Foos { get; set; }
}

但输出结果是,对于每个Icollection,EF会创建一个简单的多对多表。 那可能吗?使用EF创建三重关系?

1 个答案:

答案 0 :(得分:2)

可能是:

public class FooCooBoo
{
    [Key, ForeignKey("Foo")]
    public int FooId { get; set; }
    [Key, ForeignKey("Coo")]
    public int CooId { get; set; }
    [Key, ForeignKey("Boo")]
    public int BooId { get; set; }

    public virtual Foo { get; set; }
    public virtual Boo { get; set; }
    public virtual Coo { get; set; }
}

然后必须在某些配置类中设置导航属性。

相关问题