The result of a query cannot be enumerated more than once. even I user ToList.

Gaurang Thakkar 1 Reputation point
2021-01-29T05:21:12.493+00:00

I get following error on EF6 when trying to go over list for different output.
I have read that we have to use ToList to solve this. But in my case, even if I user new variable at each stage, I am getting same error.

below is sample code for the same
var branchList = (
from br in db.BranchTbls
join ct in db.CityTbls on br.CityID equals ct.CityID
into ctLeft
from ctL in ctLeft.DefaultIfEmpty()

                where br.IsActive == true
                select new
                {
                    br.BranchID,
                    br.BranchName,
                    ctL.CityName,
                }
            ).ToList();
            var lrdetailsTemp1 = branchList
                .Select(o =>
                    new
                    {
                        detail = o,
                        lrs = db.SP_GetPendingLoadLR(0, 0, (int)o.BranchID)
                    }
                ).ToList();
            var lsdetailsTemp2 = lrdetailsTemp1
            .Select(o =>
                new
                {
                    o.detail.BranchID,
                    o.detail.BranchName,
                    o.detail.CityName,
                    Cnt = o.lrs.Count(),
                    TotGrWt = o.lrs.Sum(x => x.GrossWt)
                }
                ).ToList()
            .Where(o => o.Cnt > 0)
            .OrderBy(o => o.CityName)
            .ThenBy(o => o.BranchName)
            .ToList();
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,438 questions
{count} votes