背景
今日在生產環境碰到如下錯誤
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、在進行洗掉時首先移除主鍵物體(如果存在)再進行操作
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/222357.html
標籤:.NET技术
