Search code examples
asp.net-mvc-3entity-framework-4.1valueinjecter

Open DataReader when mapping from EF 4.1 code first and ValueInjecter


I am using Entity Framework 4.1 code first with ASP.NET MVC 3 and Razor view and ValueInjecter.

My view model:

public class ProductViewModel
{
     public int Id { get; set; }
     public string SKU { get; set; }
     public string Name { get; set; }
     public ICollection<Specification> Specifications { get; set; }
}

Model class:

public class Product : IEntity
{
     public int Id { get; set; }
     public string SKU { get; set; }
     public string Name { get; set; }
     public virtual ICollection<Specification> Specifications { get; set; }
}

My action method where I return a list of products and then I need to map each product to a view model.

public ActionResult JsonGetProductList()
{
     IEnumerable<Product> productList = productService.GetAll();

     // Mapping
     IList<ProductViewModel> viewModelList = productList.Select(c => new ProductViewModel().InjectFrom(c)).Cast<ProductViewModel>().ToList();
}

It is giving errors on the mapping part with the following error:

There is already an open DataReader associated with this Command which must be closed first.

How would I fix this?


Solution

  • That error appears when you Lazy Load a property of the results before the DataReader of the original query get closed. You can call the ToList method after the GetAll to force the complete query execution or you can add the MultipleActiveResultSets config to your connection string to allow multiple DataReaders like this:

    connectionString="data source=YourServer;Integrated Security=SSPI; Initial Catalog=YourDB;MultipleActiveResultSets=true"