插入具有数据库中已存在的相关实体集合的实体
我有两个具有多对一关系的对象:
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(); } ); }
也许我对这两种方法都错了,那么处理上述情况的正确方法是什么?
上述就是C#学习教程:插入具有数据库中已存在的相关实体集合的实体分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。
如若转载,请注明出处:https://www.ctvol.com/cdevelopment/1012932.html