实体框架4.1 - code第一:许多一对多的关系 [英] Entity Framework 4.1 - Code First: many-to-many relationship

查看:121
本文介绍了实体框架4.1 - code第一:许多一对多的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立这样的关系(A区是x的其他区域附近)

I want to build a relation like this ( a Zone is in the neighbourhood of x other zones )

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是不正确的......我怎么能得到这样一个结构来上班?

Unfortunately this won't work, because the FKs generated by EF are not correct... How can i get a structure like this to work?

3区为例:1区,2区,3区

Example with 3 Zones: Zone 1, Zone 2, Zone 3

2区, 3区

1区

区域1

任何意见?

推荐答案

您的映射是不正确的。您正在创建自参照实体,所以你需要单独收集的传入和传出的关系。一个集合是不够的。

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.

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

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

这篇关于实体框架4.1 - code第一:许多一对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆