Entity framework 实体框架和纯POCO更新

Entity framework 实体框架和纯POCO更新,entity-framework,Entity Framework,如何使用EntityFramework4对纯POCO对象进行更新 假设我更改了此人的名字并以以下方式调用存储库: public User Update(User user) { //User originalUser = GetUser(user.UserId); //Is there a way to update the values that are only changed? context.Users.Attach(u

如何使用EntityFramework4对纯POCO对象进行更新

假设我更改了此人的名字并以以下方式调用存储库:

    public User Update(User user)
    {
        //User originalUser = GetUser(user.UserId);

        //Is there a way to update the values that are only changed?

        context.Users.Attach(user);
        context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
        return user;
    }
我不希望null值将数据库更新为null。例如,假设我将
LastName
作为属性,但将对象传递给update函数时,该属性为null。我是否必须获得originalUser,然后相应地更新每个属性

       "update each property accordingly?"
不,你可以用

       context.ObjectStateManager.TryGetObjectStateEntry(newItem, out entity);

      // this will gives you the entity present in db and after that I suggest to write your code to change the state and save.
也建议你阅读 有关跟踪实体更改的详细信息,请参见