实体框架和纯POCO更新

时间:2011-01-13 17:59:16

标签: entity-framework

如何使用实体框架4对纯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。例如。假设我有LastName作为属性,但在将对象传递给更新函数时,它为null。我是否必须获取originalUser然后相应地更新每个属性?

1 个答案:

答案 0 :(得分:0)

       "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.

还建议您阅读this 有关跟踪POCO实体

中的更改的详细信息
相关问题