c# - EntityFramework 更新部分模型

标签 c# asp.net-mvc windows entity-framework

我正在使用存储库模式和 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/

相关文章:

C# 从您的资源中一次播放多个音频文件?

c# - 如何检查 Windows 应用商店应用程序中是否存在文件?

c# - 使用单声道在 Linux 中获取 MAC 地址

windows - Delphi 和 XP 嵌入式

c# - 如何计算 IEnumerable<int> 中 int[] 中的每个数字存在多少次?

c# - 指定单个方法作为多个 Controller URL 的目标

asp.net-mvc - Webform 属性上的内联代码

asp.net - ASP.NET MVC RC 中的 SetAttemptedValue 发生了什么?

c++ - 可以安全共享指针数据的多线程库?

windows - 需要产生稳定的 10mSec 中断