EF Core 如何根据对象属性更新实体
EF Core how to update entity based on object properties
我正在使用 .net core 和 ef core 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;
}
我正在使用 .net core 和 ef core 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;
}