DragonMasa
DragonMasa

Reputation: 63

The Result of a Query Cannot be Enumerated More than Once (C#) (Entity Framework) (Stored Procedure)

When I get to db.GetLabelComponentsByLabelID(LabelIDs.ElementAt(i).Value.ToString()).ToList()

I get the following exception: The Result of a Query Cannot be Enumerated More than Once

I tried to change LabelComponents by calling ToList() like this answer suggested.

long? GroupID = db.GetGroupIDByName("PrintTest").SingleOrDefault();
ObjectResult<long?> LabelIDs = db.GetLabelIDSFromGroupingsByGroupID(GroupID.ToString());
for (int i = 0; i < LabelIDs.Count(); i++)
{
    var LabelComponents = db.GetLabelComponentsByLabelID(LabelIDs.ElementAt(i).Value.ToString()).ToList();
    List<Component> Label = new List<Component>();

    for(int j = 0; j < LabelComponents.Count(); j++)
    {
        ....
        ....

Upvotes: 3

Views: 3629

Answers (1)

DavidG
DavidG

Reputation: 118947

You need ToList on the first db call because you are enumerating the LabelIDs value multiple times. LabelIDs.Count runs the query the first time, then LabelIDs.ElementAt runs it again later on.

Upvotes: 3

Related Questions