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.

字面意思

 

 

解决思路

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

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

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

1 // User -> Receipt validation
2 private bool canUserAccessA(int aID)
3 {
4     int userID = WebSecurity.GetUserId(User.Identity.Name);
5     int aFound = db.Model.AsNoTracking().Where(x => x.aID == aID && x.UserID==userID).Count();
6 
7     return (aFound > 0); //if aFound > 0, then return true, else return false.
8 }

 

 

总结
1、查询时让EF不要跟踪

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

 

关注公众号:UP技术控   获取更多资讯

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值