开发者

ObjectContext update an object from a detached state

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?


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

context.DetectChanges();

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:

ObjectStateManager.ChangeObjectState(data, EntityState.Modified);


Use simply:

public void Update(BaseObject data, entitySetName)
{
    AttachTo(entitySetName, data);
    ObjectStateManager.ChangeObjectState(data, EntityState.Modified);
    SaveChanges();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜