EF Core的一个紧急bug,我这样修改
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、在進行刪除時首先移除主鍵實體(如果存在)再進行操作
總結
以上是生活随笔為你收集整理的EF Core的一个紧急bug,我这样修改的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Dapr牵手.NET学习笔记:用dock
- 下一篇: 怎么才能把项目做烂?!