EF Core的一个紧急bug,我这样修改
1
背景
今日在生產(chǎn)環(huán)境碰到如下錯(cuò)誤
ASP.NET MVC項(xiàng)目?Repository層中,Delete總是失敗
another entity of the same type already has the same primary key value
具體錯(cuò)誤提示:
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該方法可能會對某人有所幫助,但在這種情況下將無濟(jì)于事,因?yàn)樵趯⑽臋n加載到Edit GET控制器功能中時(shí)已經(jīng)對其進(jìn)行了跟蹤。附加將引發(fā)完全相同的錯(cuò)誤。
我在這里遇到的問題是由canUserAccessA()在更新對象a的狀態(tài)之前加載A實(shí)體的函數(shù)引起的。這正在破壞被跟蹤的實(shí)體,并且正在將對象的狀態(tài)更改為Detached。
解決方案是進(jìn)行修改canUserAccessA(),以使不會跟蹤正在加載的對象。AsNoTracking()查詢上下文時(shí)應(yīng)調(diào)用函數(shù)。
// 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
總結(jié)
1、查詢時(shí)讓EF不要跟蹤
2、在進(jìn)行刪除時(shí)首先移除主鍵實(shí)體(如果存在)再進(jìn)行操作
總結(jié)
以上是生活随笔為你收集整理的EF Core的一个紧急bug,我这样修改的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Dapr牵手.NET学习笔记:用dock
- 下一篇: 怎么才能把项目做烂?!