实体框架和纯POCO更新 [英] Entity framework and pure POCO update
本文介绍了实体框架和纯POCO更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用实体框架4对纯POCO对象进行更新?
How do I do an update on a pure POCO object using entity framework 4?
我说我更改了该人的名字并以这种方式调用存储库:
Lets say I change the person's first name and call the repository in this manner:
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
作为属性,但是将对象传递给更新函数时,它为null。我是否必须获取originalUser,然后相应地更新每个属性?
I dont want null values to update the database to null. For eg. Suppose I have LastName
as a property but when passing the object to the update function, it was null. Am I going to have to get the originalUser and then update each property accordingly?
推荐答案
"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.
这篇关于实体框架和纯POCO更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文