[英]Entity Framework 4.1 - Code First: many-to-many relationship
I want to build a relation like this ( a Zone is in the neighbourhood of x other zones )我想建立这样的关系(一个区域在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; }
}
Unfortunately this won't work, because the FKs generated by EF are not correct... How can i get a structure like this to work?不幸的是,这不起作用,因为 EF 生成的 FK 不正确......我怎样才能让这样的结构工作?
Example with 3 Zones: Zone 1, Zone 2, Zone 3 3 个区域的示例:1 区、2 区、3 区
Zone 2, Zone 3 2 区、3 区
Zone 1 1区
Zone1区域 1
Any advice?有什么建议吗?
Your mapping is not correct.您的映射不正确。 You are creating self referencing entity so you need separate collection for incoming and outgoing relations.
您正在创建自引用实体,因此您需要单独收集传入和传出关系。 Single collection is not enough.
单一收藏是不够的。
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; }
}
You don't need to map junction table unless you also want to add some additional properties to the relation.您不需要 map 联结表,除非您还想向关系添加一些其他属性。
If you want only single collection you must use fluent mapping:如果您只想要单个集合,则必须使用流畅的映射:
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();
}
}
Dave,戴夫,
How about just:怎么样:
public class Zone {
public string Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Zone> Neighours { get; set; }
}
Or am I missing something?还是我错过了什么? Do you NEED to model the neighbourhood as an external entity for some other reason?
由于其他原因,您是否需要将 model 邻居作为外部实体? I wonder what database-schema the Entity-Framework would generate for that... I'm NOT an expert, in fact I'm a noob in this area.
我想知道 Entity-Framework 会为此生成什么数据库模式……我不是专家,事实上我是这个领域的菜鸟。 I don't THINK it has a problem with self-referncing tables like this... aleast nothing I've read so far indicates it.
我不认为像这样的自引用表有问题......至少到目前为止我读过的任何内容都没有表明这一点。 Let's try it and find out;-)
让我们尝试一下并找出答案;-)
Cheers.干杯。 Keith.
基思。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.