ios85
ios85

Reputation: 2134

DataReader must be closed First and my LINQ Query

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);
}

Upvotes: 2

Views: 3888

Answers (1)

Guffa
Guffa

Reputation: 700152

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())

Upvotes: 7

Related Questions