我想建立这样的关系(一个区域在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个区域的示例:3 Zones: Zone 1, Zone 2, Zone 3
Zone 1 Neighours: Zone 2, Zone 3
Zone 2 Neighbours: Zone 1
Zone 3 Neighbours: Zone1
有什么建议吗?
您的映射不正确。您正在创建自引用实体,因此需要传入和传出关系的单独集合。单收集是不够的。
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(); } }