我正在使用存储库模式和 Entity Framework 开发 mvc 项目,现在我的表单上有一个示例模型
示例模型
1) 姓名
2) 年龄
3) 地址
4) 注意事项
5) 更新日期
我在编辑表单上只显示以下数据
1) 姓名
2) 年龄
3) 地址
现在,如果我使用存储库更新缺少属性值的模型,notes, dateupdated 字段将变为空。
我的问题是如何使用存储库(存储库中不提供 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();
}
关于c# - EntityFramework 更新部分模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9820540/