[英]EF Core in Update Records with Multiple Child Records with possibility that some are deleted from UI
所以我在我的应用程序中使用 EF 核心。 我有这些示例模型:
产品.cs
public class Product{
public int Id {get;set;}
public string Name {get;set;}
public ICollection<ProductDetail> Details {get;set;}
}
ProductDetail.cs
public class ProductDetail {
public int Id {get;set;}
public string Location {get;set;}
public Product Product {get;set;}
public int ProductId {get;set;}
}
这是我的 UI JSON 格式的示例数据
{
"id": 1,
"name": "Updated Product Name",
"details": [
{ "id": 1, "productId": 1, "location": "Updated location 1" },
{ "id": 2, "productId": 1, "location": "Updated location 2" }
]
}
这是我的更新方法。 如果我从详细信息中更新数据,这工作正常。
...
context.Products.Update(products)
但我的问题是,如果我删除这样的数据怎么办:
这是我的 UI JSON 格式的示例数据
{
"id": 1,
"name": "Updated Product Name",
"details": [
{ "id": 1, "productId": 1, "location": "Updated location 1" }
]
}
到目前为止,我创建的是删除所有记录然后重新创建新记录,但这似乎不是一个好习惯,因为我只想从 ui 中删除不存在的内容,而只是更新详细信息中的其他数据作为一部分.Update
EF 的。
编辑:
此外,在进入UpdateMethod
之前还有 mapper 方法。 这里是:
private Product SaveMapper(ProductDto productDto)
{
foreach (var detail in productDto.ProductDetails) {
detail.Product = null; // I put null here because it has string value name from the ui. Example, the actual product name.
}
return mapper.Map<Product>(productDto);
}
我在我的更新中称之为
public async bool UpdateProductService(ProductDto productDto){
return await repo.Update(SaveMapper(productDto));
}
有关如何正确执行此操作的任何帮助?
尝试以下方法 -
public void MyProductUpDateMethod(Product product)
{
// fetch the existing entity with child list
var dbProduct = context.Products.Include(p => p.Details)
.FirstOrDefault(p => p.Id == product.Id);
// set the properties
dbProduct.Name = product.Name;
dbProduct.Details = product.Details;
// save changes
context.SaveChanges();
}
如果您添加、删除或修改任何子实体,这应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.