2011-01-13 103 views
0

如何使用实体框架4对纯POCO对象进行更新?实体框架和纯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; 
    } 

我不想空值来更新数据库为空。例如。假设我有LastName作为属性,但是在将对象传递给更新函数时,它是空的。我将不得不得到原始用户,然后相应地更新每个属性?

回答

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实体