c# – EntityFramework更新部分模型
我正在使用mvc專案,具有儲存庫模式和實體框架,現在在我的表單上我有一個示例模型
的SampleModel
1)名稱
2)年齡
3)地址
4)筆記
5)更新日期
我只顯示編輯表單上的以下資料
1)名稱
2)年齡
3)地址
現在如果我使用儲存庫更新缺少屬性值的模型,那麼note,dateupdated欄位將變為null.
我的問題是如何使用儲存庫僅更新幾個選定的屬性(tryupdatemodel在儲存庫中不可用),我不想呼叫原始物件並使用更新的模型對映屬性.
有什麼辦法嗎
您只能更新欄位的子集:
using (var context = new YourDbContext()) { context.SamepleModels.Attach(sampleModel); DbEntityEntry<SameplModel> entry = context.Entry(sampleModel); entry.Property(e => e.Name).IsModified = true; entry.Property(e => e.Age).IsModified = true; entry.Property(e => e.Address).IsModified = true; context.SaveChanges(); }
或在ObjectContext API中:
using (var context = new YourObjectContext()) { context.SamepleModels.Attach(sampleModel); ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(sampleModel); entry.SetModifiedProperty("Name"); entry.SetModifiedProperty("Age"); entry.SetModifiedProperty("Address"); context.SaveChanges(); }
http://stackoverflow.com/questions/9820540/entityframework-update-partial-model