Click here to Skip to main content
13,901,208 members
Click here to Skip to main content
Add your own
alternative version

Stats

11.9K views
6 bookmarked
Posted 29 Dec 2013
Licenced CPOL

Lazy Behavior of IQueryable

, 22 Feb 2019
Rate this:
Please Sign up or sign in to vote.
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.

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.

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.

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.

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!

License

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

Share

About the Author

Bohdan Stupak
Software Developer
Ukraine Ukraine
https://twitter.com/BohdanStupak1

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
tbayart25-Feb-19 2:02
membertbayart25-Feb-19 2:02 
GeneralMy vote of 2 Pin
johannesnestler9-Jan-14 3:34
memberjohannesnestler9-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
memberwkempf22-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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190306.1 | Last Updated 22 Feb 2019
Article Copyright 2013 by Bohdan Stupak
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid