EF Core的一个紧急bug,我这样修改

背景

今日在生产环境碰到如下错误

ASP.NET MVC项目 Repository层中,Delete总是失败

another entity of the same type already has the same primary key value

具体错误提示:

Attaching an entity of type 

'ResearchManager.Models.BigTracker_UI.Product_Tracker_Scraping' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

字面意思

2

解决思路

Attach该方法可能会对某人有所帮助,但在这种情况下将无济于事,因为在将文档加载到Edit GET控制器功能中时已经对其进行了跟踪。附加将引发完全相同的错误。

我在这里遇到的问题是由canUserAccessA()在更新对象a的状态之前加载A实体的函数引起的。这正在破坏被跟踪的实体,并且正在将对象的状态更改为Detached。

解决方案是进行修改canUserAccessA(),以使不会跟踪正在加载的对象。AsNoTracking()查询上下文时应调用函数。


// User -> Receipt validationprivateboolcanUserAccessA(intaID){intuserID = WebSecurity.GetUserId(User.Identity.Name);intaFound = db.Model.AsNoTracking().Where(x => x.aID == aID && x.UserID==userID).Count();return(aFound >0);//if aFound > 0, then return true, else return false.}

3

总结

1、查询时让EF不要跟踪

2、在进行删除时首先移除主键实体(如果存在)再进行操作

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 渐变的面目拼图要我怎么拼? 我是疲乏了还是投降了? 不是不允许自己坠落, 我没有滴水不进的保护膜。 就是害怕变得面...
    闷热当乘凉阅读 9,771评论 0 13
  • 感觉自己有点神经衰弱,总是觉得手机响了;屋外有人走过;每次妈妈不声不响的进房间突然跟我说话,我都会被吓得半死!一整...
    章鱼的拥抱阅读 6,556评论 4 5
  • 夜莺2517阅读 127,793评论 1 9
  • 版本:ios 1.2.1 亮点: 1.app角标可以实时更新天气温度或选择空气质量,建议处女座就不要选了,不然老想...
    我就是沉沉阅读 11,837评论 1 6
  • 我是一名过去式的高三狗,很可悲,在这三年里我没有恋爱,看着同龄的小伙伴们一对儿一对儿的,我的心不好受。怎么说呢,高...
    小娘纸阅读 8,695评论 4 7