EF 4.1单个班级中的多对多关系

时间:2011-05-27 17:52:54

标签: many-to-many entity-framework-4.1

我有一个具有多个多对多关系的类映射到同一个二级类。我的EquipmentSet类有两个Equipment对象数组,而Equipment类也有一个EquipmentSets数组,用于确定设备属于哪个集合。

EF仅为第二个多对多关系生成查找表。如何告诉EF为两者生成查找表?使用下面的代码时,仅生成表“ModelSpecificEquipment”。 “GlobalEquipment”表永远不会生成。

public partial class EquipmentSet 
{
    public int Id { get; set; }
    public List<Equipment> Global { get; protected set; }
    public List<Equipment> ModelSpecific { get; protected set; }

    public EquipmentSet()
    {
        Global = new List<Equipment>();
        ModelSpecific = new List<Equipment>();
    }
}


public partial class Equipment
{
    public int Id { get; set; }
    public List<EquipmentSet> EquipmentSets { get; set; }

    public Equipment()
    {
    }
}



public class DataContext : DbContext
{
    public DbSet<Equipment>  Equipment { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Equipment>()
            .HasMany<EquipmentSet>(x => x.EquipmentSets)
            .WithMany(x => x.Global)
            .Map(x =>
            {
                x.MapLeftKey("EquipmentId");
                x.MapRightKey("EquipmentSetId");
                x.ToTable("GlobalEquipment");
            });

        modelBuilder.Entity<Equipment>()
            .HasMany<EquipmentSet>(x => x.EquipmentSets)
            .WithMany(x => x.ModelSpecific)
            .Map(x =>
            {
                x.MapLeftKey("EquipmentId");
                x.MapRightKey("EquipmentSetId");
                x.ToTable("ModelSpecificEquipment");
            });
        base.OnModelCreating(modelBuilder);
    }
}

此时,EF创建的数据库仅包含3个表:EquipmentSets,Equipments,ModelSpecificEquipments。缺少GlobalEquipments。

1 个答案:

答案 0 :(得分:1)

我认为不可能映射这个。您不能将一侧的两个端点与关系另一侧的一个端点相关联。你可能需要这样的东西:

public partial class Equipment
{
    public int Id { get; set; }
    public List<EquipmentSet> GlobalEquipmentSets { get; set; }
    public List<EquipmentSet> ModelSpecificEquipmentSets { get; set; }

    public IEnumerable<EquipmentSet> EquipmentSets
    {
        get
        {
            return GlobalEquipmentSets.Concat(ModelSpecificEquipmentSets);
            // catch cases when one or both of the sets are null.
        }
    }
}

EquipmentSets这里只是一个未映射到数据库的只读助手。

然后,您可以在GlobalGlobalEquipmentSets之间创建多对多关系,并在ModelSpecificModelSpecificEquipmentSets之间建立多对多关系。