[英]Can't delete a row using entity framework
我遇到的問題是使用實體時無法刪除行。 我能夠找到該行,但是出現錯誤后我得到了下一個錯誤:
附加信息:存儲更新,插入或刪除語句影響了意外的行數(0)。 自加載實體以來,實體可能已被修改或刪除。 有關了解和處理樂觀並發異常的信息,請參見http://go.microsoft.com/fwlink/?LinkId=472540 。
我嘗試在程序包管理器控制台中更新數據庫,嘗試了幾種不同的刪除記錄的方式,但目前還不走運。 自動遷移已啟用。
以下是我當前嘗試使用的代碼。
var ctx = new Context();
ApplicationUser user = new ApplicationUser { UserName = myUsername };
ctx.Users.Attach(user);
ctx.Users.Remove(user);
ctx.Entry(user).State = EntityState.Modified;
ctx.SaveChanges();
感謝所有幫助。 我已經為此努力了好幾個小時。
在EF中刪除實體的常用方法如下:
DbSet<T>
定位實體。 這可能是從集合中檢索實體或將其附加到集合; DbSet<T>.Remove
; DbContext.SaveChanges
。 由於ApplicationUser.UserName
不是主鍵屬性,因此您需要查找實體。 附加在這里沒有意義DbSet<T>.Attach
告訴上下文將具有給定主鍵的實體視為已存在且未修改的實體,但是您無需設置主鍵值(可能是在構造函數中生成的,因為您正在使用GUID?)。
像這樣:
// assuming, that user names are not unique
var user = ctx.Users.FirstOrDefault(_ => _.UserName == myUsername);
if (user != null)
{
ctx.Users.Remove(user);
cts.SaveChanges();
}
您刪除實體,然后將其標記為已修改。 刪除行:
ctx.Entry(user).State = EntityState.Modified;
怎么樣:
var ctx = new Context();
ApplicationUser user = new ApplicationUser { UserName = myUsername };
ctx.Entry(user).State = EntityState.Deleted
ctx.SaveChanges();
或者只是刪除有關修改記錄的行。 不需要它,因為首先您要刪除它,請不要更改。 其次,.remove函數已經將其設置為正確的狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.