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(intaID) 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、在進行刪除時首先移除主鍵實體(如果存在)再進行操作