ABP vNext 踩坑实录(一)

在使用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的类的实例,问题至此被解决。

 

posted @ 2020-12-13 21:18  代码改变人参  阅读(1997)  评论(0编辑  收藏  举报