Entity Framework 4.1 - Code First:多对多关系

3
我希望建立这样的关系(一个区域与其他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

有什么建议吗?

@Dave:抱歉,我对Zone和ZoneNeighbourhood之间的关系不是很清楚。我想你的意思是一个区域可以在另一个区域中,而后者可能是另一个“超级区域”的子区域......是这样吗? - corlettk
不,我的意思就像我添加的例子一样...它就像是一个隐含的邻居关系...就像人与人之间的关系一样:史密斯先生是琼斯先生的邻居,所以琼斯先生隐含地也是史密斯先生的邻居。 - David
2个回答

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

除非你想要向关系添加一些附加属性,否则不需要映射联接表。

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

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

好的回答,谢谢。但是当我像你在第一种情况中建议的那样使用类时,我遇到了“Zone”类型上属性“NeighourTo”的“InversePropertyAttribute”无效的问题。 - David
@David:那是因为属性名称的类型错误。我已经编辑过了,现在应该可以工作了。 - Ladislav Mrnka

1

Dave,

只需要这样怎么样:

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

还是我有什么地方理解不对吗?你是否需要将邻居模型化为外部实体以满足其他需求?我想知道Entity-Framework会为此生成什么数据库模式... 我并不是专家,事实上在这个领域我是个新手。我认为它不会对这样的自引用表格有问题... 至少到目前为止我读到的没有任何迹象表明有问题。让我们试一试,看看结果如何;-)

干杯。Keith。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接