在使用CrudAppService的UpdateAsync方法時,報錯如下:
The instance of entity type 'OrderItem' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
搜索到的大部分資料都把解決思路指向“AsNoTracking”,如:
https://blog.csdn.net/chengmin1989/article/details/88941525
但該方案於我並不適用。
經分析,原因是:
Order類中包含導航屬性OrderItem,而OrderItem類中又包含導航屬性Dish,UpdateAsync方法對這種較復雜的類支持不足或是需要進行相關的配置(暫未查到,歡迎知情的朋友指出)才能正確調用。
條條大路通羅馬,因此在查閱了一些博客和文檔后,結合我的實際需求,解決方案如下:
_context.Entry(dish).State = EntityState.Unchanged;
_context.Entry(orderItem).State = EntityState.Added;
_context.Entry(order).State = EntityState.Modified;
_context.Orders.Update(order);
var result = await _context.SaveChangesAsync();
上方代碼中的_context是一個繼承自AbpDbContext的類的實例,問題至此被解決。