简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM