![](/img/trans.png)
[英]EF Core cannot update entity with two navigation properties to same object (other entity)
[英]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.