简体   繁体   中英

EF Core in Update Records with Multiple Child Records with possibility that some are deleted from UI

So I'm using EF core in my app. I have these sample models which are:

Product.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;}
}

Here's my sample data from UI JSON format

{
    "id": 1,
    "name": "Updated Product Name",
    "details": [
         { "id": 1, "productId": 1, "location": "Updated location 1" },
         { "id": 2, "productId": 1, "location": "Updated location 2" }
    ]
}

And this is my update method. Which is working fine if I update the data from the details.

...
context.Products.Update(products)

But my problem is, what if I deleted a data like this:

Here's my sample data from UI JSON format

{
    "id": 1,
    "name": "Updated Product Name",
    "details": [
         { "id": 1, "productId": 1, "location": "Updated location 1" }
    ]
}

So far, what I created is to delete all the records then re-create new ones but it seems not a good practice though since I only want to remove what is not existing from the ui and just update the other data in the details as part of the .Update EF.

EDIT:
Additionally, there's mapper method before going to the UpdateMethod . Here it is:

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);
}

And I call this in my update

public async bool UpdateProductService(ProductDto productDto){
    return await repo.Update(SaveMapper(productDto));
}

Any help on how can do this properly?

Try the following approach -

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();
}

This should work if you added, removed or modified any child entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM