Linq使用中的ToList注意事项

在使用Linq时,如果查询逻辑太复杂,可以拆分为多个Linq查询,下一个Linq在上一个Linq查询的结果上继续操作,这样逻辑清晰,又不会出错。但在使用ToList的时候需要注意,最常见碰到的错误是:

LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[xxx] ToList[xxx](System.Collections.Generic.IEnumerable`1[xxx])' method, and this method cannot be translated into a store expression.

今天碰到的这个错误纠结了我好久,不管怎么样,就是不给ToList。

ToList 就是把LINQ查询结果放在内存中,想到这里就明白了,下一个Linq要使用上一个Linq的查询结果,如果select new 后面什么都没有,是使用的匿名类,那你尽可放心地使用。如果new后面是一个类,这就得注意了,下一个Linq在使用上一个Linq的结果时需要把查询结果放在内存中再使用,否则就会报错。至于为啥要放进去,估计原因就是内存中堆栈神马的。具体原因有待探究。贴点代码做个示例就结束随笔了:

            var examscore = query1.FirstOrDefault();
            if (examscore == null)
                return new ExamScorePrintModel();

            var query2 = from si in _examScoreItemRepository.Table
                         join sc in _examScoreCourseRepository.Table on si.Id equals sc.ExamScoreItemId
                         let course = sc.ExamCourse
                         where si.ExamScoreId == examscore.ExamScoreId
                         select new RecordItem
                                    {
                                        ExamScoreItemId = si.Id,
                                        DeductedScores = sc.DeductedScores,
                                        Remark = sc.Remark,
                                        CourseName = course.CourseName,
                                    };
View Code
            var items = query2.ToList();

            var query3 = from q in items
                         group q by q.ExamScoreItemId
                             into grouping
                             select new ExamRecord
                                        {
                                            ExamScoreItemId = grouping.Key,
                                            RecordItems = grouping.ToList(),
                                        };
            examscore.ExamRecords = query3.ToList();
View Code
原文地址:https://www.cnblogs.com/young2012/p/3246405.html