我总是这样定义我的多对多关系:
modelBuilder.Entity<PriceList>()
.HasMany(i => i.Brands)
.WithMany(p => p.PriceLists)
.Map(m =>
{
m.ToTable("PriceListsBrands");
m.MapLeftKey("PriceListId");
m.MapRightKey("BrandId");
});
它一直运作良好。
但现在我正在使用“实体框架扩展批量插入”(https://entityframework-extensions.net/bulk-insert)我想批量插入到PriceListsBrands
表中。
所以我必须为每个sé创建关系对象......
(我通常不需要,因为我已经有了导航属性Brands
和PriceLists
)
public class PriceListBrand
{
public long PriceListId { get; set; }
public virtual PriceList PriceList { get; set; }
public long BrandId { get; set; }
public virtual Brand Brand { get; set; }
public PriceListBrand()
{
}
}
最后调用BulkInsert:
var priceListsBrands = new List<PriceListBrand>();
// Populate
// ...
dbContext.BulkInsert(priceListsBrands);
但后来我得到了这个例外:
EntityType 'PriceListBrand' 没有定义键。定义此 EntityType 的键。
我尝试在之前的 FluentAPI 代码上方添加以下 FluentAPI 定义:
modelBuilder.Entity<CustomerPriceListBrand>()
.HasKey(e => new { e.PriceListId, e.BrandId })
.ToTable("PriceListsBrands");
但后来我得到了这个例外:
已经定义了具有模式 'dbo' 和表 'PriceListsBrands' 的 EntitySet 'PriceListBrand1'。
(注意“1”:它试图定义两次关系)
所以问题是:我怎样才能既定义“多对多”关系又定义关系对象呢?