背景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技術控 獲取更多資訊