mo_maat
mo_maat

Reputation: 2240

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

Upvotes: 1

Views: 481

Answers (1)

Moho
Moho

Reputation: 16498

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

Upvotes: 1

Related Questions