shamim
shamim

Reputation: 6770

How to insert record with many to many relational tables

work on asp.net mvc5 ef-6.Face problem with many to many relational table data insertion.My classes models are

public class Product
{
    public long ProductID { get; set; }
    public string ProductName { get; set; }

    //navigation property to Supplier
    public virtual ICollection<ProductSupplier> ProductSupplier { get; set; }
}

public class Supplier
{      
    public long SupplierID { get; set; }
    public string SupplierName { get; set; }

    // navigation property to Product
    public virtual ICollection<ProductSupplier> ProductSupplier { get; set; }
}

public class ProductSupplier
{
    public long ProductID { get; set; }
    public long SupplierID { get; set; }
    public virtual Product Product { get; set; }
    public virtual Supplier Supplier { get; set; }
    public bool IsActive { get; set; }  
}

How to insert records on above classes.Will first i need to insert on Product then Supplier then ProductSupplier.

Upvotes: 0

Views: 100

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239270

You essentially just have a M2M with a payload here. With that, you'll need to set the Product/Supplier on ProductSupplier before saving that relationship. So something along these lines:

var product = new Product();
var supplier = new Supplier();
var productSupplier = new ProductSupplier
{
    Product = product,
    Supplier = supplier
};
db.ProductSuppliers.Add(productSupplier);
db.SaveChanges();

For simplicity, I only dealt with the relationships here. Obviously you'd want to intialize/add the other data on the entities. Also, note that it's only necessary to explicitly add the ProductSupplier instance to its DbSet. By virtue of being attached to that instance, the Product and Supplier instances will also be added and saved. You can of course still do that explicitly, instead, if you like.

Upvotes: 1

Related Questions