Entity Framework 4.1 - How to "Force" EF To Go To DB Instead of Using Graph?
Asked Answered
G

1

6

Here's the scenario, i have a website, which in a single HTTP request (HTTP POST), i need to do the following:

  1. Grab an object (let's say "Tag")
  2. Save some other object (let's say "Question")
  3. Get a fresh copy of "Tag".
  4. Redirect to another page, which needs a fresh copy of "Tag".

Behind the scenes, 2) involves database-side triggers that affects data on "Tag".

So when i do 3), EF is pulling the same copy of the object from step 1), since it's in the graph/internal memory (e.g same connection/context)

I need a "fresh" copy of the object.

In the past, i've used Detach, then i perform an EF query and the latest object in fetched from the DB.

But i don't have access to the object here per-se (i have a DTO, which is returning from my repository), so i don't have anything to pass to the Detach method.

Is there any way to say:

var fresh = db.Tags.Find(1, ignoreGraph: true)

Or is there another alternative?

As mentioned, i'm on Entity Framework 4.1, C# 4 (and ASP.NET MVC 3)

The only solution i can see right now is to pass a querystring parameter to the next page, which then grabs the fresh copy (since it's a new context, new graph, etc).

Grochow answered 12/10, 2011 at 4:33 Comment(4)
possible duplicate of #7639719Reiter
@nathan - possibly, but the answer there won't help, since i don't have access to the umbrella object (or the tag object here) for the context.Refresh(RefreshMode.StoreWins,umbrella) call.Grochow
and also, that is EF4, not EF4.1. It appears the "Refresh" method has been removed from DbContext.Grochow
@nathan - yeah, that would work (see my below answer), but it needs access to the object, much like Detach.Grochow
G
13

Found my answer, i think:

Context.Entry<T>(entity).Reload()

Trying now...

Grochow answered 12/10, 2011 at 4:47 Comment(5)
I don't have access to entity, only dtoEntity.Grochow
If you want to refresh entity you must know which entity to refresh, don't you? If you know key of the entity you can still find it in change tracker and after that reload it.Bradford
@Ladislav, i have a unique index, not the entity. E.g i do Find().SingleOrDefault(x => x.UniqueUri == someUri).Grochow
Still it is unique identification so you should be able to find the entity in context.ChangeTracker.Entries<EntityType>().Select(e => e.Entity).FristOrDefault(...) - the only think you have to now is unique identification and type of entity.Bradford
@Ladislav - yep, i guess i could do that. Just means i need to leak more EF logic through to my repository interface. No other option i guess.Grochow

© 2022 - 2024 — McMap. All rights reserved.