背景api
今日在生产环境碰到以下错误app
ASP.NET MVC项目 Repository层中,Delete老是失败函数
具体错误提示:this
Attaching an entity of type spa
'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.code
字面意思对象
解决思路blog
Attach该方法可能会对某人有所帮助,但在这种状况下将无济于事,由于在将文档加载到Edit GET控制器功能中时已经对其进行了跟踪。附加将引起彻底相同的错误。ip
我在这里遇到的问题是由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 }
总结
一、查询时让EF不要跟踪
二、在进行删除时首先移除主键实体(若是存在)再进行操做
关注公众号:UP技术控 获取更多资讯