c# - Entity Framework 4.1 - 代码优先 : many-to-many relationship

标签 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 区邻居:

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

关于c# - Entity Framework 4.1 - 代码优先 : many-to-many relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5802072/

相关文章:

c# - 将服务引用添加到 SOAP 服务不会生成异步方法

c# - 如何在 C# 中使用 Task<bool> 函数输出字符串值

c# - 方法 'System.Linq.Queryable.SelectMany System.Linq.IQueryable 的类型参数

c# - 可以返回不同类型的通用方法

c# - 连接过程后 Linq 更新不同的表

php - 删除带有索引的大型 MySQL 表的性能

sql - 面试题最优解

c# - 如何在 C# 中截取 Winforms 控件/窗体的屏幕截图?

c# - 将文件复制到不同的目录

.net - 嵌入式脚本环境的优点/缺点?