Sunday, August 23, 2009

ASP.NET MVC - The query results cannot be enumerated more than once

I'm not a fan of Microsoft tehnology, but I find their MVC solution framework pretty good. Of course when it's copy-pasted from cool stuff like RoR and similiar technology ;-)

Anyway, here goes a small tip. 

Let's say that you have a controller and a method like this:
public ActionResult Details(int id)
{
    var fooDataContext = new FooDataContext();
    var foo = fooDataContext.sprocFooSearch(id);
    ViewData["Foo"] = foo;
    return View();
}
This is sufficient and you'll probably write most of the code like this. But if you wish to put your hands in the 'foo' before passing it in View you probably want to convert result to List using ToList method because it can be enumerated only once because of DataReader and you'll receive a following error "Exception Details: System.InvalidOperationException: The query results cannot be enumerated more than once."
Solution: 
public ActionResult Details(int id)
{
    var fooDataContext = new FooDataContext();
    var foo = fooDataContext.sprocFooSearch(id).ToList();
    if (!foo.Any())
        return View("NotFound");
    ViewData["Foo"] = foo;
    return View();
}

No comments:

Post a Comment