简体   繁体   中英

EF Core how to update entity based on object properties

I am using .net core and ef core 2.1. I have the following piece of code where I try to get a list of entities from my context. I then want to perform some operations based on that list and then update the entity then save it. How would I go about doing this? I'm open to suggestions on how to better structure this.

item = await _context.Items
    .Where(i => i.ItemId == xxx)
    .ToListAsync();

IList<Item> updatedItems;

if (items.Count > 0) {
    var docEntry = _context.Entry(documents);

    //cast the collection to Document type
    updatedItems = (IList<Items>)ds.PerformAction(items);  //perform some action in another service class and return a collection of updated items

    //now I want to merge/update my context to reflect the updated items
    foreach (Item itm in updatedItems){
        //update my context items
        item.ItemColor = itm.ItemColor //for matched items
    }
}

await _context.SaveChangesAsync();

Assuming you can't change ds.PerformAction to perform the changes on the original objects, join the results with the original items list to map the updated item to the original item entity:

var mappedItems = items.Join( 
    updatedItems, 
    // join criteria (pk selector)
    oi => oi.ItemId, 
    ii => ii.ItemId,
    ( oi, ii ) => new
        {
            OriginalItem = oi,
            UpdatedItem = ii,
        } );

Then perform whatever you need to do in a loop or similar construct:

foreach( var at in mappedItems )
{
    at.OriginalItem.ItemColor = at.UpdatedItem.ItemColor;
}

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