插入具有数据库中已存在的相关实体集合的实体

我有两个具有多对一关系的对象:

public class Product { public int ProductID { get; set; } public string ProductName { get; set; } public virtual Collection ProductInventorys { get; set; } = new Collection(); } public class ProductInventory { public int ProductInventoryID { get; set; } public string ProductInventoryName { get; set; } public int ProductID { get; set; } public virtual Product ProductFK { get; set; } } 

我想在数据库中添加一个带有现有ProductInventory集合的新ProductInventory (我的API将具有ProductInventoryID数组的输入),因此我执行如下操作:

 private void AddProduct(int[] productInventoryIDs) { Product newProduct = new Product(); newProduct.Name = "New Product"; // Here I have no clue which would be the correct way...should I use // Approach A - fetch each related "ProductInventory" entity from database, // then add them into the collection of my new base entity - Product) productInventoryIDs.ToList().Foreach(p => { newProduct.ProductInventorys.Add(_dbContext.ProductInventory.FindById(p)) } ); _dbContext.Products.Add(newProduct); _dbContext.SaveChanges(); // Approach B: Save base "Product" entity first, then grab the new ProductID, // then fetch each "ProductInventory" from database and assign the foreign key with the new "ProductID" value, and then save each _dbContext.Products.Add(newProduct); var newProductID = _dbContext.SaveChanges(); productInventoryIDs.ToList().Foreach(pi => { var existedProductInventoryFromDb = _dbContext.ProductInventory.FindById(pi); existedProductInventoryFromDb.ProductID = newProductID; _dbContext.SaveChanges(); } ); } 
  • 通过使用方法(A) ,我的newProduct无法保存,我查看了SQL资源,看起来它也试图插入ProductInventory ,尽管这些ProductInventory已经存在于数据库中。 我猜那是因为我将它们添加到我的基本实体的集合中?

  • 通过使用方法(B) ,我觉得这样做有点尴尬,因为它就像为一个对象提取和保存多次一样,我怀疑我是否正在以正确的方式行事……

也许我对这两种方法都错了,那么处理上述情况的正确方法是什么?