我試圖找到使用 EF 核心僅更新特定欄位的最佳方法。問題是有很多欄位,并且將每個欄位標記為已修改,更改其值會使代碼變得非常冗長和復雜。
有沒有辦法至少設定新值并在一個命令中標記為已修改?
這就是我的代碼現在的樣子:
context.Entry(obj).Property("name").IsModified = true;
obj.name="Dan";
對于每個欄位(大約 30 個欄位,但表要大得多),它一直在繼續。
我也試過這個:
context.Entry(obj).Property("name").CurrentValue="Dan";
context.SaveChangesAsync();
但它不會更新任何記錄。
任何幫助,將不勝感激!
uj5u.com熱心網友回復:
從資料庫中獲取物件后,只需更新屬性的值并呼叫SaveChanges. EF 將生成一個查詢,該查詢僅使用新值更新屬性。
var myObj = await this.context.FindAsync(id);
myObj.Property1 = 42;
myObj.Property2 = "new value";
...
await this.context.SaveChangesAsync();
PS 確保啟用更改跟蹤。
uj5u.com熱心網友回復:
我通常使用這個演算法
var existingObj = await Context.Set<obj>().FindAsync(id);//or use FirstOrDefault()
if (existingObj== null) return ...error;
existingObj.Name="name"
Context.Entry(existingObj).Property(i=>i.Name).IsModified = true;
Context.SaveChanges();
uj5u.com熱心網友回復:
我必須補充的是:
context.ChangeTracker.AutoDetectChangesEnabled = true;
然后我可以像這樣更新它:
context.Entry(obj).Property("name").CurrentValue="Dan";
context.Entry(obj).Property("lastName").CurrentValue="Bar";
.
.
.
await context.ApplyChangesAsync();
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377995.html
上一篇:如何將SQL轉換為C#
