0

I am new to MVC and Entity and I am trying to access data from one of my tables.I am using the following code to access the database, but I am getting the following error:The operation cannot be completed because the DbContext has been disposed. This is my stack trace and code:

 at System.Data.Entity.Core.Objects.ObjectContext.get_Connection()
 at System.Data.Entity.Core.Objects.Internal.ObjectQueryState.get_DefaultStreamingBehavior()
 at System.Data.Entity.Core.Objects.Internal.ObjectQueryState.get_EffectiveStreamingBehavior()
 at System.Data.Entity.Core.Objects.EntitySqlQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
 at System.Data.Entity.Core.Objects.ObjectQuery.ToTraceString()
 at System.Data.Entity.Internal.Linq.InternalSet`1.ToString()
 at System.Data.Entity.Infrastructure.DbQuery`1.ToString()
 at System.IO.TextWriter.Write(Object value)
 at System.IO.TextWriter.SyncTextWriter.Write(Object value)
 at System.Console.Write(Object value)
 at VideoTrainingSystem.Controllers.AdminController.Index() in C:\Users\lg701\Documents\Visual Studio 2015\Projects\VTS2\VTS\Controllers\AdminController.cs:line 18

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.Mvc;
 using VTS.Models;

 namespace VTS.Controllers
 {
     public class AdminController : Controller
     {
        // GET: Admin
        public ActionResult Index()
        {
           try
           {
              var test = GetUsers();
           }
           catch (Exception ex)
           {
               Console.Write(ex);
           }

        return View();
    }


    public IQueryable<User> GetUsers()
    {
        IQueryable<User> users;
        using (UserContext userContext = new UserContext())
        {
            users = userContext.Users;
        }

        if (users.Any() == false)
        {
            return null;
        }
        else
        {
            return users;

        }
    }
}

}

3 Answers3

2

The problem is in your GetUsers method. users = userContext.Users; code line gives you a query to operate on and when you try to use that query with users.Any() == false line you will get specified error, because your are trying to use UserContext after it is disposed (UserContext is disposed in the end of using block). Even if you use this line inside using block the returned IQuerable will be useless. Try to use Unit of Work and Repository patterns. You can follow this tutorial to learn more about that patterns. Initially it may seem long solution (or overkill) for a simple error, but once you get used to this, it is very convenient and flexible to use and you will save a lot of time by doing so in the long run.

Adil Mammadov
  • 8,476
  • 4
  • 31
  • 59
0

You need to wrap your return statement with the "using" block, otherwise the database context will have expired, and the "users" object is reliant on that context, since it consists of data selected from the database:

public IQueryable<User> GetUsers()
{
    IQueryable<User> users;
    using (UserContext userContext = new UserContext())
    {
        users = userContext.Users;

        if (users.Any() == false)
        {
            return null;
        }
        else
        {
            return users;
        }
    }
}
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • Thank you, I modified my code according your suggestion but I am getting the same error. –  Oct 03 '16 at 13:41
  • No, this won't and can't work. Your minimal solution has to contain a ToList(), see the duplicate. – H H Oct 03 '16 at 13:50
0

When do you use using statement, the framework dispose all resources allocated for resources. You need to move the if/else block to using block;

 public IQueryable<User> GetUsers() 
 {
    IQueryable<User> users;
    using (UserContext userContext = new UserContext())
    {
        users = userContext.Users;

        if (users.Any() == false)
        {
            return null;
        }
        else
        {
            return users;
        }
    }
}