简体   繁体   中英

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++)
    {
        ....
        ....

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM