问题
I have a class with multiple many to many relationships mapping to the same secondary class. My EquipmentSet class has two arrays of Equipment objects, and the Equipment class also has an array of EquipmentSets to determine which sets the equipment is a part of.
EF is only generating a lookup table for the second Many to Many relationship. How can I tell EF to generate lookup tables for both? When the code below is used, only the table "ModelSpecificEquipment" is generated. The table "GlobalEquipment" never gets generated.
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);
}
}
Again, at this point the database that EF creates only contains 3 tables: EquipmentSets, Equipments, ModelSpecificEquipments. GlobalEquipments is missing.
回答1:
I think it is not possible to map this. You cannot relate two endpoints on one side to one single endpoint on the other side of a relationship. You will probably need something like this:
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
is here only a readonly helper which isn't mapped to the database.
You can then create a many-to-many relationship between Global
and GlobalEquipmentSets
and another many-to-many relationship between ModelSpecific
and ModelSpecificEquipmentSets
.
来源:https://stackoverflow.com/questions/6155953/ef-4-1-multiple-many-to-many-relationships-in-single-class