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

Dav*_*vid 3 .net c# 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; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

1区邻居:

2区,3区

2区邻居:

1区

3区邻居:

1区

有什么建议?

Lad*_*nka 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; }
}
Run Code Online (Sandbox Code Playgroud)

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

如果您只想要单个集合,则必须使用流畅的映射:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)