简体   繁体   中英

Entity Framework Refresh Entity Does Not Refresh Its Foreign Keys

When marking an entity for deletion, and saving changes, sometimes the operation fails due to foreign key constraints for example. In this case, i notify the user and refresh the entity. The problem is that the entity does not get fully refreshed - its foreign keys stays empty.

For example :

//EditableEntity.SomeCollection --> Populated...

ContextManager.CurrentObjectContext.DeleteObject(EditableEntity);

try
{
    ContextManager.CurrentObjectContext.SaveChanges();
}
catch (Exception err)
{
    ContextManager.CurrentObjectContext.Refresh(System.Data.Objects.RefreshMode.StoreWins, EditableEntity);
}

//EditableEntity.SomeCollection --> Empty!!

Please help, Thanks, Oran

Well, it seems that after recreating the EDM, and rebuilding the project, the above procedure works fine.

To conclude the solution : When marking an object for deletion, it behaves as it was 'detached' from the object context losing its related parents and collections but is actually still in the 'attached' state. If the delete opertaion is canceled of any reason, the usage of this object related objects and collections, will raise an exception. To solve this we need to 'attach' the object back to the object context. The problem is that the object is still marked as 'attached'.

To solve this simply refresh the object using :

ContextManager.CurrentObjectContext.Refresh(RefreshMode.StoreWins, item);

Hope it helps, Oran

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM