bassen
bassen

Reputation: 191

how do i refresh data in Entity framework internal cache

I have a application where i am working with entityframework code first. I have a problem with EF implementing identity map pattern, EF caches some entities in the memory. What i would like to do is to add a newdesk to a user. So when i login with the user that i added the newsdesk to they will be able to use the application. But this doesn´t seem to work. If i manually refresh my localdb i can login in.

I have tried to Refresh the context but i can´t get it to work. this is the code snippet from my add newsdesk method. Don´t know if it is of any help but i'am working with a global context. I would be grateful for any help.

        var user = DatabaseContext.Users.Single(u => u.Id == userid);
        var newsdesk = DatabaseContext.Newsdesks.Single(u => u.Id == newsdeskid);

        user.Newsdesk = newsdesk;

        DatabaseContext.SaveChanges();
        DatabaseContext.Reload(user);
        var objContext = ((IObjectContextAdapter)DatabaseContext).ObjectContext;
        objContext.Refresh(RefreshMode.StoreWins, user);

Upvotes: 0

Views: 990

Answers (1)

cuongle
cuongle

Reputation: 75316

Based on the code you showed which uses DatabaseContext as static, so I guess you are using DatabaseContext as singleton, right?

The problem in your code is you are keeping the lifetime of DbContext longer then expected. In your case, it would be living as application lifetime and lead to problems:

  1. Problem you got, data is obsolete in internal cache, so you have to refresh manually.
  2. The internal cache increases for the time being and will cause to the memory leak at the end.

The best practice to use DbContext are:

  1. In web application, keep the lifetime DbContext is per request.
  2. In win application, keep the lifetime DbContext is per thread.

You can use IoC container to make this work.

Upvotes: 1

Related Questions