简体   繁体   English

EF Core 如何根据对象属性更新实体

[英]EF Core how to update entity based on object properties

I am using .net core and ef core 2.1.我正在使用 .net 核心和 ef 核心 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:假设您无法更改ds.PerformAction以对原始对象执行更改,将结果与原始项目列表连接起来以将更新的项目映射到原始项目实体:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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