1
背景
今日在生产环境碰到如下错误
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 validation
private bool canUserAccessA(int aID)
{int userID = WebSecurity.GetUserId(User.Identity.Name);int aFound = 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、在进行删除时首先移除主键实体(如果存在)再进行操作