Mil*_*lan 16 c# windows asp.net-mvc entity-framework
我正在研究mvc项目,具有存储库模式和实体框架,现在在我的表单上我有一个示例模型
SampleModel
1)名称
2)年龄
3)地址
4)注释
5)更新日期
我只在编辑表格上显示以下数据
1)姓名
2)年龄
3)地址
现在,如果我使用存储库更新缺少属性值的模型,则notes,dateupdated字段为空.
我的问题是如何使用存储库更新少数选定的属性(tryupdatemodel在存储库中不可用),我不想调用原始对象并使用更新的模型映射属性.
有什么办法,一定有.
Lad*_*nka 21
您只能更新字段子集:
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();
}
Run Code Online (Sandbox Code Playgroud)
或者在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();
}
Run Code Online (Sandbox Code Playgroud)