繁体   English   中英

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

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

我正在使用 .net 核心和 ef 核心 2.1。 我有以下一段代码,我尝试从我的上下文中获取实体列表。 然后我想根据该列表执行一些操作,然后更新实体然后保存它。 我该怎么做呢? 我愿意接受有关如何更好地构建它的建议。

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

假设您无法更改ds.PerformAction以对原始对象执行更改,将结果与原始项目列表连接起来以将更新的项目映射到原始项目实体:

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

然后在循环或类似结构中执行您需要执行的任何操作:

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