Reputation: 191
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
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:
The best practice to use DbContext
are:
DbContext
is per request.DbContext
is per thread.You can use IoC container to make this work.
Upvotes: 1