Insert entity with a collection of related entities which already exist in the database

醉酒当歌 提交于 2019-12-08 11:10:48

问题


I have two objects with a many-to-one relationship:

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

public class ProductInventory
{
   public int ProductInventoryID { get; set; }
   public string ProductInventoryName { get; set; }
   public int ProductID { get; set; }
   public virtual Product ProductFK { get; set; }
}

I would like to add a new Product with a collection of existing ProductInventory (my API would have an input of ProductInventoryID array) into the database, so I perform like:

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();
        }
    );
}
  • By using approach (A), my newProduct failed to save and I looked into SQL resource, looks like it is trying to insert ProductInventory as well, although these ProductInventory already exist in the database. I guess that's because I add them into my base entity's collection?

  • By using approach (B), I am feeling a little awkward for doing that as it's like fetching and saving multiple times for just one object, I doubt if I am doing the correct way...

Maybe I am wrong at both approaches, so what would be the correct way to deal with above scenario?

来源:https://stackoverflow.com/questions/51120596/insert-entity-with-a-collection-of-related-entities-which-already-exist-in-the-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!