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

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生成的FKS不正确...我如何获得这样的结构?

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

区域1邻居:

2区,第3区

区域2邻居:

区域1

区域3邻居:

区域1

有建议吗?

有帮助吗?

解决方案

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

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

其他提示

戴夫,

怎么样:

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

还是我想念什么?您是否需要出于某些其他原因将社区建模为外部实体?我想知道实体 - 框架将为此产生的数据库 - 施加...我不是专家,实际上我是这个领域的菜鸟。我认为这样的自我引用表没有问题。让我们尝试一下并找出答案;-)

干杯。基思。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top