user6440175 user6440175 - 2 years ago 133
C# Question

The operation cannot be completed because the DbContext has been disposed - MVC Error:

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()
var test = GetUsers();
catch (Exception ex)

return View();

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

if (users.Any() == false)
return null;
return users;



Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download