实体框架4.1 - 代码优先:多对多关系

时间:2011-04-27 09:39:44

标签: c# .net sql entity-framework entity-framework-4.1

我想建立这样的关系(区域位于x其他区域附近)

public class Zone
{
    public string Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<ZoneNeighourhood> ZoneNeighourhoods { get; set; }
}

public class ZoneNeighbourhood
{
    public virtual Zone Zone1 { get; set; }
    public virtual Zone Zone2 { get; set; }
}

不幸的是,这不起作用,因为EF生成的FK不正确...我怎样才能让这样的结构起作用?

3个区域的示例:区域1,区域2,区域3

1区Neighours:

2区, 3区

第2区邻居:

1区

第3区邻居:

1区

有什么建议吗?

2 个答案:

答案 0 :(得分:9)

您的映射不正确。您正在创建自引用实体,因此您需要单独收集传入和传出关系。单一收藏是不够的。

public class Zone 
{
    public string Id { get; set; }
    public string Name { get; set; }
    [InverseProperty("NeighbourOf")]
    public virtual ICollection<Zone> NeighbourTo { get; set; }
    [InverseProperty("NeighbourTo")]
    public virtual ICollection<Zone> NeighbourOf { get; set; }
}

除非您还想为关系添加一些其他属性,否则无需映射联结表。

如果您只想要单一收藏,则必须使用流畅的映射:

public class Zone 
{
    public string Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Zone> Neighours { get; set; }
}

public class Context : DbContext
{
    public DbSet<Zone> Zones { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Zone>()
                    .HasMany(z => z.Neighbours)
                    .WithMany();
    }
}

答案 1 :(得分:1)

戴夫,

如何:

public class Zone {
    public string Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Zone> Neighours { get; set; }
}

或者我错过了什么?出于其他原因,您是否需要将邻域建模为外部实体?我想知道Entity-Framework会为那个生成什么样的数据库模式...我不是专家,事实上我是这个领域的菜鸟。我不认为它有像这样的自我参考表的问题...到目前为止我读过的东西都没有表明它。让我们试一试,找出答案; - )

干杯。基思。