среда, 30 сентября 2015 г.

Entity Framework: Reload newly created object / Reload navigation properties

Environment

ASP.NET MVC 4 application, EntityFramework 6

Problem


Unable to reload the updated properties of an object from the database, and navigation properties.

Scenario

I do processing Post-request for object creation in the controller's action .
The object itself passed in the Action as parameter.

I usually do this sequence

...
check values
save object
additional actions after saving
...

From the client side a new object comes "clean" / without navigational properties.
I add it to the context and save.
Once saved, I want to do the extra processing in which I need the navigation properties,
but the problem is that EF caches object and reloading does not update the navigation properties. They remain empty.

Solution

Before you read the object from database it must be disconnected from the context.

I got to do it this way:

public void Detach (T entity)
{
            ((IObjectContextAdapter) _db) .ObjectContext.Detach (entity);
}

The solution found here
Entity Framework Code First - No Detach () method on DbContext
http://stackoverflow.com/questions/4168073/entity-framework-code-first-no-detach-method-on-dbcontext

Related Links


Entity Framework Code First - No Detach() method on DbContext
http://stackoverflow.com/questions/4168073/entity-framework-code-first-no-detach-method-on-dbcontext

Reload an entity and all Navigation Property Association- DbSet Entity Framework
http://stackoverflow.com/questions/9081244/reload-an-entity-and-all-navigation-property-association-dbset-entity-framework

How to update an entity's navigation properties in Entity Framework
http://stackoverflow.com/questions/10542209/how-to-update-an-entitys-navigation-properties-in-entity-framework

Entity Framework POCO - Refresh a navigation property
http://stackoverflow.com/questions/3839166/entity-framework-poco-refresh-a-navigation-property

Комментариев нет:

Отправить комментарий