2

I am trying to use LINQ to select a bunch of Name objects from my database using EF. The problem is that I am getting an error:

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

Project is a Type that contains information about that project. It is a navigation property on the name class. What is wrong with my LINQ query that causes this error.

var allNames = from n in _db.DCENames
               orderby n.BrandName ascending
               select n;

foreach (Name name in allNames)
{
    NameDbModel data = new NameDbModel();
    data.id = name.Id;
    data.BrandName = name.BrandName; 
    data.MarkType = name.Project.MarkType;
    data.DateAdded = name.DateAdded;
    data.PrimarySector = name.Project.PrimarySector;
    data.ProjectName = name.Project.ProjectName; 
    data.Status = name.Project.ProjectStatus;
    data.ProjectId = name.Project.ProjectId;
    data.Notes = "";
    model.Add(data);
}
joce
  • 9,624
  • 19
  • 56
  • 74
ios85
  • 2,104
  • 7
  • 37
  • 55
  • Potential duplicate of [Entity Framework: There is already an open DataReader associated with this Command](http://stackoverflow.com/questions/4867602/entity-framework-there-is-already-an-open-datareader-associated-with-this-comma) – Malcolm O'Hare Mar 28 '13 at 20:29

1 Answers1

7

The LINQ query will not fetch the data, it will only create an enumerable that can fetch the data, so the data reader is open until you have fetched the last item.

Use the ToList method to read all the records into a list before using them:

foreach (Name name in allNames.ToList())
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • That could cause multiple enumerations of the list, it's best he wraps his query in brackets then calls `.ToList()` on that. +1 for the deferred execution explanation though. – Mathew Thompson Mar 28 '13 at 20:33
  • ToList can create an extraordinarily large structure in memory, depending on how many rows are returned. Best to include the child records in the initial query and just enumerate the result. – Eric J. Mar 15 '18 at 23:38