日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

EF Core的一个紧急bug,我这样修改

發(fā)布時(shí)間:2023/12/4 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 EF Core的一个紧急bug,我这样修改 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。