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

c# entity-framework extension-methods

Question

I'm trying to use an extension method that converts from my Database type because I'm new to EF.User my information classUserInfo .
If it matters, I'm utilizing a database first.

The mistake is produced by my code below.

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)
{
    //...
}

Although I can understand why it would do it, I'm baffled as to why the output of the where statement isn't being saved into theusers object?

So I guess my major issue is why it doesn't work and my secondary concern is how should I use EF and extension methods?

1
34
2/19/2016 10:45:36 AM

Accepted Answer

I'm led to conclude that IQueryable requires an active context in order to function by this question and response. This is what you ought to try in its place:

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)
{
    ...
}
35
5/23/2017 12:10:18 PM

Popular Answer

items revealed asIQueryable<T> and IEnumerable<T> until they are iterated through or otherwise accessible, such as being constructed into a program, do they actually "execute"List<T> When EF returns an error,IQueryable<T> It is really just creating something that is capable of data retrieval; the retrieval isn't truly done until you consume it.

In order to get a sense of this, set a breakpoint when theIQueryable as opposed to when the.ToList() is known as. (From within the parameters of the data context, as Jofry has appropriately noted.) Work is done to gather the data during theToList() call.

As a result, you must maintain theIQueryable<T> inside of the parameters of the data context.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow