0

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.

AGB
  • 2,230
  • 1
  • 14
  • 21
shamim
  • 6,640
  • 20
  • 85
  • 151
  • 1
    Are you getting any specific error messages? – Cam Bruce May 16 '16 at 17:07
  • @ Cam Bruce ,thanks for your reply,Looking for syntax how to insert,After a lot of googling get something create object of ProductSupplier,then fill this object property with Supplier and Product object but this always insert on not perform any update. – shamim May 16 '16 at 17:46

1 Answers1

1

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.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • ,thanks for your reply.When scenario is insert only then your syntax work perfectly but problem aries when product need to update and supplier need to add or vice versa. – shamim May 17 '16 at 17:05
  • The nature of `ProductSupplier` is such that it cannot exist without a `Product` and a `Supplier`, so I'm not seeing the issue. Whether the product, supplier or both are new or existing, everything still works the same. – Chris Pratt May 17 '16 at 18:54