Click here to Skip to main content
15,886,058 members
Articles / Programming Languages / C#
Tip/Trick

Lazy Behavior of IQueryable

Rate me:
Please Sign up or sign in to vote.
3.74/5 (17 votes)
22 Feb 2019CPOL 18.9K   7   4
Here’s a workaround how to fix exception "DbContext has been disposed"

Introduction

Some of you may have encountered exception DbContext has been disposed. Here is basic explanation of why this error occurs and how to fix it.

Image 1

Background

For our needs, let’s use a simple ASP.NET MVC application and Entity Framework to access database.

Source Code

For instance, let’s assume we have source code that returns collection of all products, which have price greater than or equal to 0.

C#
public ActionResult Index()
{
    return View(GetAllProducts());
}

private IEnumerable<Product> GetAllProducts()
{
    using (var context = new Context.Context())
    {
        var list = context.Products.Where(p => p.Price >= 0);
        return list;
    }
} 

If we set a breakpoint, we’ll see that query actually doesn’t execute, as some of you may have expected.

Image 2

When such IEnumerable/IQueryable instance is passed into view, the above mentioned exception is raised. To execute this query, we simply cast such instance to list.

C#
public ActionResult Index()
{
    return View(GetAllProducts());
}

private IEnumerable<Product> GetAllProducts()
{
    using (var context = new Context.Context())
    {
        var list = context.Products.Where(p => p.Price >= 0).ToList();
        return list;
    }
} 

And voila!

Image 3

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Ukraine Ukraine
Team leader with 8 years of experience in the industry. Applying interest to a various range of topics such as .NET, Go, Typescript and software architecture.

Comments and Discussions

 
GeneralMy vote of 1 Pin
tbayart25-Feb-19 2:02
professionaltbayart25-Feb-19 2:02 
GeneralMy vote of 2 Pin
johannesnestler9-Jan-14 3:34
johannesnestler9-Jan-14 3:34 
GeneralRe: My vote of 2 Pin
Bohdan Stupak17-Apr-14 5:21
professionalBohdan Stupak17-Apr-14 5:21 
GeneralRe: My vote of 2 Pin
wkempf22-Feb-19 3:24
wkempf22-Feb-19 3:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.