我正在使用.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();
答案 0 :(得分:1)
假设您无法更改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;
}