2011-01-13 105 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實體