1

I've always defined my many-to-many relationships like this:

modelBuilder.Entity<PriceList>()
    .HasMany(i => i.Brands)
    .WithMany(p => p.PriceLists)
    .Map(m =>
    {
        m.ToTable("PriceListsBrands");
        m.MapLeftKey("PriceListId");
        m.MapRightKey("BrandId");
    });

And it has always worked well.

But now that I'm using "Entity Framework Extensions Bulk Insert" (https://entityframework-extensions.net/bulk-insert) I want to bulk insert into PriceListsBrands table.

So I had to create the relationship object per sé...
(which I usually don't need because I already have the navigation properties Brands and 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()
    {
    }
}

To finally call BulkInsert:

var priceListsBrands = new List<PriceListBrand>();

// Populate
// ...

dbContext.BulkInsert(priceListsBrands);

But then I'm getting this exception:

EntityType 'PriceListBrand' has no key defined. Define the key for this EntityType.

I tried adding the following FluentAPI definition above my previous FluentAPI code:

modelBuilder.Entity<CustomerPriceListBrand>()
             .HasKey(e => new { e.PriceListId, e.BrandId })
             .ToTable("PriceListsBrands");

But then I'm getting this exception:

The EntitySet 'PriceListBrand1' with schema 'dbo' and table 'PriceListsBrands' was already defined.

(Notice the "1": it is trying to define twice the relationship)

So the question is: how can I both define a "many to many" relationship and a relationship object too?

sports
  • 7,851
  • 14
  • 72
  • 129

0 Answers0