ObjectContext 从分离状态更新对象
我有一个带有更新方法的 ObjectContext。该方法采用通用对象作为参数。我需要将此对象附加到 ObjectContext 并使用对象所做的更改更新数据库。例如,我创建一个新对象,该对象与数据库中的实体具有相同的键,但某些字段不同。我想将对象附加到数据库中相应的实体,并让它保存新对象的更改。这是我在更新方法中的内容:
public void Update(BaseObject data, entitySetName)
{
AttachTo(entitySetName, data);
Refresh(RefreshMode.ClientWins, data);
SaveChanges();
}
刷新后,数据会被数据库中的字段覆盖。省略刷新也不会更新数据库记录。我是不是少了一步?
I have an ObjectContext with an update method. The method takes a generic object as a parameter. I need to attach this object to the ObjectContext and update the database with the changes the object had. example, I create a new object that has the same key as and entity in the database but some of the fields are different. I want to attach the object to its corresponding entity in the database and have it save the changes the new object has. Here is what i have in the Update method:
public void Update(BaseObject data, entitySetName)
{
AttachTo(entitySetName, data);
Refresh(RefreshMode.ClientWins, data);
SaveChanges();
}
After the refresh, the data get overwritten by the fields from the database. Leaving out the refresh also does not update the database record. Am I missing a step?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果进行了任何更改,则 DetectChanges() 方法会将实体状态更新为已修改。
来自 MSDN:“在没有更改跟踪代理的 POCO 实体中,当调用 DetectChanges 方法时,已修改属性的状态将更改为“已修改”。保存更改后,对象状态将更改为“未更改”。”
此外,您可以将状态设置为已修改,以便您的方法始终如此。无论是否有任何更改,都会尝试更新:
The DetectChanges() method will update the entitystate to modified if any changes have been made.
From MSDN: "In POCO entities without change-tracking proxies, the state of the modified properties changes to Modified when the DetectChanges method is called. After the changes are saved, the object state changes to Unchanged."
Additionally you could just set the state to modified so your method always trys to update regardless of whether anything has changed or not with:
使用简单:
Use simply: