title: There is Already an open DataReader that must be closed first
body: <p>In my mapping logic layer(Model to ViewModel) I am trying to populate a <code>SelectListItem</code> for use with an HTML.DropDownListFor helper in my edit view.</p>
  
  <p>I attempted using a query in the following code sample to retrieve a list of brand names to populate the SelectListItem, but triggered the following exception:</p>
  
  <blockquote>
    <p>There is already an open DataReader associated with this Command which
    must be closed first.</p>
  </blockquote>
  
  <h2>Mapping</h2>
  
  <pre><code>public class MedicalProductMapper
  {
      private MvcMedicalStoreDb _db; // DataContext class
  
      public MedicalProductMapper(MvcMedicalStoreDb db)
      {
          _db = db;
      }    
      public MedicalProductViewModel GetMedicalProductViewModel(MedicalProduct source)
      {
          MedicalProductViewModel viewModel = new MedicalProductViewModel();
  
          viewModel.ID = source.ID; 
          viewModel.Name = source.Name;
          viewModel.Price = source.Price;
          viewModel.BrandID = source.BrandID;
  
          // This following line produces the exception
          viewModel.BrandName = _db.Brands.Single(b =&gt; b.ID == source.BrandID).Name;
  
          var queryBrands = from b in _db.Brands
                            select b;
  
          viewModel.BrandSelectListItem = queryBrands as IEnumerable&lt;SelectListItem&gt;;
  
          return viewModel;
      }
  }
  </code></pre>
  
  <p>I understand that there is an easy fix, by enabling <strong>Multiple Active Result Sets (MARS)</strong> in the connection string, but I'd like to know if there's a way to do what I want without modifying the connection string.</p>
  
  <p>Here are some more classes in case they are helpful in figuring out this problem:</p>
  
  <h2>Edit view</h2>
  
  <pre><code>@model MvcMedicalStore.Models.MedicalProductViewModel
  
  @{
      ViewBag.Title = "Edit";
  }
  
  &lt;h2&gt;Edit&lt;/h2&gt;
  
  @using (Html.BeginForm()) {
      @Html.AntiForgeryToken()
      @Html.ValidationSummary(true)
  
      &lt;fieldset&gt;
          &lt;legend&gt;MedicalProduct&lt;/legend&gt;
  
          @Html.HiddenFor(model =&gt; model.ID)
  
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(model =&gt; model.Name)
          &lt;/div&gt;
          &lt;div class="editor-field"&gt;
              @Html.EditorFor(model =&gt; model.Name)
              @Html.ValidationMessageFor(model =&gt; model.Name)
          &lt;/div&gt;
  
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(model =&gt; model.Price)
          &lt;/div&gt;
          &lt;div class="editor-field"&gt;
              @Html.EditorFor(model =&gt; model.Price)
              @Html.ValidationMessageFor(model =&gt; model.Price)
          &lt;/div&gt;
  
          // BRAND NAME
          &lt;div class="editor-label"&gt;
              @Html.LabelFor(model =&gt; model.BrandName)
          &lt;/div&gt;
          &lt;div class="editor-field"&gt;
              @Html.DropDownListFor(model =&gt; model.BrandName, Model.BrandSelectListItem)
              @Html.ValidationMessageFor(model =&gt; model.BrandName)
          &lt;/div&gt;
  
          &lt;p&gt;
              &lt;input type="submit" value="Save" /&gt;
          &lt;/p&gt;
      &lt;/fieldset&gt;
  }
  
  &lt;div&gt;
      @Html.ActionLink("Back to List", "Index")
  &lt;/div&gt;
  
  @section Scripts {
      @Scripts.Render("~/bundles/jqueryval")
  }
  </code></pre>
  
  <h2>Controller:</h2>
  
  <pre><code>public class MedicalProductController : Controller
  {
      private MvcMedicalStoreDb _db = new MvcMedicalStoreDb();
  
      //
      // GET: /MedicalSupply/
  
      public ActionResult Index()
      {
          var viewModel = _db.Products.AsEnumerable()
              .Select(product =&gt; GetMedicalProductViewModel(product));
          return View(viewModel);
      }
  
      public MedicalProductViewModel GetMedicalProductViewModel(MedicalProduct product)
      {
          var mapper = new MedicalProductMapper(_db);
  
          return mapper.GetMedicalProductViewModel(product);            
      }
      public MedicalProduct GetMedicalProduct(MedicalProductViewModel viewModel)
      {
          var mapper = new MedicalProductMapper(_db);
  
          return mapper.GetMedicalProduct(viewModel);
      }
  
      //
      // GET: /MedicalSupply/Edit/5
  
      public ActionResult Edit(int id = 0)
      {
          MedicalProduct medicalProduct = _db.Products.Find(id);
          if (medicalProduct == null)
          {
              return HttpNotFound();
          }
  
          var viewModel = GetMedicalProductViewModel(medicalProduct);
          return View(viewModel);
      }
  
      //
      // POST: /MedicalSupply/Edit/5
  
      [HttpPost]
      [ValidateAntiForgeryToken]
      public ActionResult Edit(MedicalProduct medicalProduct)
      {
          if (ModelState.IsValid)
          {
              _db.Entry(medicalProduct).State = EntityState.Modified;
              _db.SaveChanges();
              return RedirectToAction("Index");
          }
  
          var viewModel = GetMedicalProductViewModel(medicalProduct);
          return View(viewModel);
      }
  }
  </code></pre>
  
  <h2>Stack Trace</h2>
  
  <blockquote>
    <p>[InvalidOperationException: There is already an open DataReader
    associated with this Command which must be closed first.]<br>
    System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand
    command) +5287423<br>
    System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String
    method, SqlCommand command) +20<br>
    System.Data.SqlClient.SqlCommand.ValidateCommand(String method,
    Boolean async) +155<br>
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
    cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
    method, TaskCompletionSource`1 completion, Int32 timeout, Task&amp; task,
    Boolean asyncWrite) +82<br>
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
    cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
    method) +53<br>
    System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
    behavior, String method) +134<br>
    System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
    behavior) +41<br>
    System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
    +10    System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
    entityCommand, CommandBehavior behavior) +437</p>
    
    <p>[EntityCommandExecutionException: An error occurred while executing
    the command definition. See the inner exception for details.]<br>
    System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
    entityCommand, CommandBehavior behavior) +507<br>
    System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext
    context, ObjectParameterCollection parameterValues) +730<br>
    System.Data.Objects.ObjectQuery<code>1.GetResults(Nullable</code>1
    forMergeOption) +131<br>
    System.Data.Objects.ObjectQuery<code>1.System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator()
    +36    System.Linq.Enumerable.Single(IEnumerable</code>1 source) +179    System.Data.Objects.ELinq.ObjectQueryProvider.b_<em>3(IEnumerable<code>1
    sequence) +41<br>
    System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable</code>1
    query, Expression queryRoot) +59<br>
    System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression
    expression) +133<br>
    System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression
    expression) +123    System.Linq.Queryable.Single(IQueryable<code>1 source,
    Expression</code>1 predicate) +287<br>
    MvcMedicalStore.Mappers.MedicalProductMapper.GetMedicalProductViewModel(MedicalProduct
    source) in c:\Users\Matt\Documents\Visual Studio
    2012\Projects\MvcMedicalStore\MvcMedicalStore\Mappers\MedicalProductMapper.cs:28
    MvcMedicalStore.Controllers.&lt;>c</em>_DisplayClass1.b_<em>0(MedicalProduct
    product) in c:\Users\Matt\Documents\Visual Studio
    2012\Projects\MvcMedicalStore\MvcMedicalStore\Controllers\HomeController.cs:28
    System.Linq.WhereSelectEnumerableIterator<code>2.MoveNext() +145<br>
    ASP._Page_Views_Home_Index_cshtml.Execute() in
    c:\Users\Matt\Documents\Visual Studio
    2012\Projects\MvcMedicalStore\MvcMedicalStore\Views\Home\Index.cshtml:25
    System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197<br>
    System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +119<br>
    System.Web.WebPages.StartPage.RunPage() +17<br>
    System.Web.WebPages.StartPage.ExecutePageHierarchy() +62<br>
    System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
    pageContext, TextWriter writer, WebPageRenderingBase startPage) +76<br>
    System.Web.Mvc.RazorView.RenderView(ViewContext viewContext,
    TextWriter writer, Object instance) +743<br>
    System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext
    viewContext, TextWriter writer) +382<br>
    System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
    +431    System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
    controllerContext, ActionResult actionResult) +39<br>
    System.Web.Mvc.&lt;&gt;c__DisplayClass1a.&lt;InvokeActionResultWithFilters&gt;b__17()
    +74    System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
    filter, ResultExecutingContext preContext, Func</code>1 continuation) +388<br>
    System.Web.Mvc.&lt;>c</em>_DisplayClass1c.b_<em>19()
    +72    System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
    controllerContext, IList<code>1 filters, ActionResult actionResult) +303<br>
    System.Web.Mvc.Async.&lt;&gt;c__DisplayClass2a.&lt;BeginInvokeAction&gt;b__20()
    +155    System.Web.Mvc.Async.&lt;&gt;c__DisplayClass25.&lt;BeginInvokeAction&gt;b__22(IAsyncResult
    asyncResult) +184    System.Web.Mvc.Async.WrappedAsyncResult</code>1.End()
    +136    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56<br>
    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult
    asyncResult) +40<br>
    System.Web.Mvc.&lt;>c</em>_DisplayClass1d.b_<em>18(IAsyncResult
    asyncResult) +40<br>
    System.Web.Mvc.Async.&lt;>c</em>_DisplayClass4.b_<em>3(IAsyncResult
    ar) +47    System.Web.Mvc.Async.WrappedAsyncResult<code>1.End() +151<br>
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
    Object tag) +59<br>
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
    Object tag) +40<br>
    System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
    System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult
    ar) +47    System.Web.Mvc.Async.WrappedAsyncResult</code>1.End() +151<br>
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
    Object tag) +59<br>
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
    Object tag) +40    System.Web.Mvc.Controller.EndExecute(IAsyncResult
    asyncResult) +39<br>
    System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult
    asyncResult) +39<br>
    System.Web.Mvc.&lt;>c</em>_DisplayClass8.b_<em>3(IAsyncResult
    asyncResult) +45<br>
    System.Web.Mvc.Async.&lt;>c</em>_DisplayClass4.b__3(IAsyncResult
    ar) +47    System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151<br>
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
    Object tag) +59<br>
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
    Object tag) +40<br>
    System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
    +40    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
    result) +38<br>
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
    +9628700    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +155</p>
  </blockquote>