Entity Framework 4.1 - Refresh is not a member of Context
Asked Answered
C

3

9

I'm trying to revert Context changes using the Context.Refresh method but It seems like Refresh is not a member of Context.

I'm using the Microsoft ADO.NET Entity Framework 4.1 RC version.

Any idea?

Cynical answered 22/10, 2011 at 23:21 Comment(0)
P
13

You are likely looking at a DbContext, which does not have a Refresh method. You can use the IObjectContextAdapter interface to get the underlying ObjectContext, and call Refresh on that.

var objectContext = ((IObjectContextAdapter)context).ObjectContext;
Pettaway answered 22/10, 2011 at 23:31 Comment(1)
Kudos "adrift", you saved the day for me. There are LOTS of answers out there to this question, and yours is by far the best! Its really too bad that DbContext doesnt support the Refresh directly? This would seem to be a very common pattern to want in multitier apps. I was getting close to just reading the object back in, and copying what changed before I saw your answer :-)Dissyllable
P
2

You can also use the Reload function on the Proxy Objects... Here is a sample to reload all modified objects:

            var modifiedEntries = context.ChangeTracker.Entries()
                .Where(e => e.State == EntityState.Modified);
            foreach (var modifiedEntry in modifiedEntries) {
                modifiedEntry.Reload();
            }
Pertinent answered 17/11, 2011 at 14:17 Comment(0)
O
0

The answer posted in this thread might help too: Refresh entity instance with DbContext

In summary though, you might try calling something like the following:

dbContext.Entry(someEntityObjectInstance).Reload();

However, someone else noted that this doesn't refresh navigation properties, so if you have to worry about refreshing navigation properties as well, you either need to Reload() all of the navigation properties as well or you will need to Detach() or Refresh() after casting to IObjectContextAdapter, or maybe just recreate your DbContext.

In my case, I frankly decided it was best just to recreate the context and re-Find() the entity:

dbContext = new Model.Entities();
someEntityObjectInstance = dbContext.SomeEntityType.Find(someEntityObjectInstanceKey);

There is arguably no simple/best answer here.

Olsewski answered 9/6, 2014 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.