JayPrime2012
JayPrime2012

Reputation: 2692

Entity Framework Many To Many Entity?

This is not another question concerning how to create a Many To Many relationship, but rather, how to actually take control of the entity that maps the relationship?

For example... Many to many relationship between table Product and table Supplier.

I need a SupplierProduct that has columns specific to a product+supplier combination.

class SupplierProduct {
    public int SupplierId { get; set; }
    public int ProductId { get; set; }

    // additional properties specific to a S+P combo: 
    public bool IsProductAssembled { get; set; }
}

Some suppliers assemble, others don't. If I have such a class, how can I use it in place of the default EF many-to-many table that it creates?

Upvotes: 2

Views: 231

Answers (1)

JLe
JLe

Reputation: 2904

Use your SupplierProduct class as relation instead:

class SupplierProduct {
    public int SupplierId { get; set; }
    public int ProductId { get; set; }

    // additional properties specific to a S+P combo: 
    public bool IsProductAssembled { get; set; }
}

class Product {
    // ... lot of properties

    // Link all the suppliers of this products
    public IList<SupplierProduct> Suppliers { get; set; }
}    

class Supplier {
    // ... lot of properties

    // Link all the product this supplier supplies
    public IList<SupplierProduct> Products { get; set; }
}

Then, configure Product to have a lot of Suppliers and Supplier to have a lot of Products. No direct relation between Product and Supplier anymore.

Configure the model binder:

modelBuilder.Entity<Product>()
    .HasMany<SupplierProduct>(p => p.Suppliers)
    .WithRequired();

modelBuilder.Entity<Supplier>()
    .HasMany<SupplierProduct>(s => s.Products)
    .WithRequired();

Upvotes: 2

Related Questions