如何只更新修改的值(EntityFramework 5.0)? [英] How to update only modified values (EntityFramework 5.0)?

查看:335
本文介绍了如何只更新修改的值(EntityFramework 5.0)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个实体,想要使用entityframework更新

I have this entity, want to update using entityframework

 EmployeeModel employee = new EmployeeModel
    {
        Id = 1000, //This one must 
        FirstName = modifiedValue,
        Email = modifiedValue, 
        LastName = originalValue,
        Phone = originalValue
    };

要更新的代码

_db.ObjectStateManager.ChangeObjectState(employee, EntityState.Modified);  
_db.SaveChanges();

这是一次更新的SQL语句

This is the SQL statement got once updated

Update Employee set Id=1138,FirstName='modifiedValue',Email='modifiedValue',LastName= 'OriginalValue',phone='originalValue' where Id=1138

但我期待这个

Update Employee set FirstName='modifiedValue', Email='modifiedValue' where Id=1138.

我不知道我在这里失踪了。请告诉我。

I dont know what I am missing here. Please let me know.

推荐答案

这是我得到的解决方案

 var entity = _db.CreateObjectSet<Employee>();
 entity.Detach(employee);
 entity.Attach(employee);

 foreach (string modifiedPro in employeeModel.ModifiedProperties){
  _db.ObjectStateManager.GetObjectStateEntry(employee).SetModifiedProperty(modifiedPro);}

  _db.SaveChanges();

仅在sql update语句中修改的值

Only modified values in the sql update statement

Update Employee set FirstName='modifiedValue', Email='modifiedValue' where Id=1138.

如果任何人都知道更好的答案,请张贴你的建议

If anybody knows better answer than this, Please post your suggestions

这篇关于如何只更新修改的值(EntityFramework 5.0)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆