Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The operation cannot be completed because the DbContext has been disposed error

I'm new to EF and I'm trying to use an extension method which converts from my Database type User to my info class UserInfo.
I'm using database first if that makes a difference?

My code below gives the error

The operation cannot be completed because the DbContext has been disposed.

try {     IQueryable<User> users;     using (var dataContext = new dataContext())     {         users = dataContext.Users                   .Where(x => x.AccountID == accountId && x.IsAdmin == false);         if(users.Any() == false)         {             return null;         }     }     return users.Select(x => x.ToInfo()).ToList(); // this line is the problem } catch (Exception ex) {     //... } 

I can see why it would do it, but I also don't understand why the result of the where statement isn't being saved into the users object?

So I guess my main question is why doesn't it work and secondly what's the right way of using extension methods and EF?

like image 496
Colin Avatar asked Nov 29 '12 02:11

Colin


1 Answers

This question & answer lead me to believe that IQueryable require an active context for its operation. That means you should try this instead:

try {     IQueryable<User> users;      using (var dataContext = new dataContext())     {         users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);          if(users.Any() == false)         {             return null;         }         else         {             return users.Select(x => x.ToInfo()).ToList(); // this line is the problem         }     }   } catch (Exception ex) {     ... } 
like image 137
JofryHS Avatar answered Sep 26 '22 12:09

JofryHS