的EntityFramework更新局部模型 [英] EntityFramework update partial model
问题描述
我的工作的MVC项目,存储库模式和实体框架,现在我的表格上,我有一个样品模型
I am working on mvc project, with repository pattern and entity framework, now on my form i have a sample model
的SampleModel结果
1)名称结果
2)年龄结果
3)地址搜索
4)笔记结果
5)更新日期搜索
SampleModel
1) name
2) age
3) address
4) notes
5) date updated
我在编辑表单结果只显示以下数据
1)名称结果
2)年龄结果
3)处理结果
I am displaying only following data on the edit form
1) name
2) age
3) address
现在如果我更新使用存储库中,票据丢失的属性值模型,dateupdated区域变空。
now if i update the model with missing property values using the repository, the notes, dateupdated field goes null.
我的问题是我如何使用资料库(tryupdatemodel在库中不可用)更新只有少数选定的属性,我不想打电话给原来的对象和性质在与更新的模型映射。
My question is how do i update only few selected properties using the repository ( tryupdatemodel not available in repository ) and i dont want to call the original object and map the properites with the updated model.
有什么办法,必须有。
推荐答案
您可以更新领域的唯一子集:
You can update only subset of fields:
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:
or in 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();
}
这篇关于的EntityFramework更新局部模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!