处理asp.net mvc5 ef-6.Face问题,包含多对多的关系表数据插入。我的类模型是
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; }
}
如何在上面的类上插入记录。首先我需要在Product然后是Supplier,然后是ProductSupplier上插入。
答案 0 :(得分:1)
你基本上只有一个有效载荷的M2M。这样,您需要在保存该关系之前在Product
上设置Supplier
/ ProductSupplier
。所以有这样的话:
var product = new Product();
var supplier = new Supplier();
var productSupplier = new ProductSupplier
{
Product = product,
Supplier = supplier
};
db.ProductSuppliers.Add(productSupplier);
db.SaveChanges();
为简单起见,我只处理了这里的关系。显然,您希望在实体上初始化/添加其他数据。另请注意,只需要将ProductSupplier
实例明确添加到其DbSet
。通过附加到该实例,还将添加并保存Product
和Supplier
实例。如果你愿意的话,你当然可以明确地这样做。