无法在 lambda 表达式中获取计数 - 不支持异常

本文关键字:不支持 异常 获取 lambda 表达式 | 更新日期: 2023-09-27 18:31:27

我正在尝试使用以下查询获取每个学生的科目数:

var selectedSubject = context.Students
                             .Include(d => d.Subjects)
                             .Select(dr => new
                                           {
                                               Name = dr.Student.FirstName,
                                               NoOfSubject = dr.Subjects.Count
                                           })
                             .ToList();

但是我得到了一个例外

EntityFramework.SqlServer 中发生了类型为"System.NotSupportedException"的未处理异常.dll

其他信息:指定的类型成员"主题"在 LINQ to 实体中不受支持。仅支持初始值设定项、实体成员和实体导航属性

无法在 lambda 表达式中获取计数 - 不支持异常

在查询具体化之前,您将无法访问IList接口上的非entity member属性(如 Count )。

要么尽早实现:

var selectedSubject = context.Students
                         .Include(d => d.Subjects)
                         // .Where() goes here, 
                         .ToList()
                         .Select(dr => new
                                       {
                                           Name = dr.Student.FirstName,
                                           NoOfSubject = dr.Subjects.Count
                                       })
                         .ToList();

或者,使用 Count() 方法,该方法可映射到 Sql 中:

var selectedSubject = context.Students
                         .Include(d => d.Subjects)
                         .Select(dr => new
                                       {
                                           Name = dr.Student.FirstName,
                                           NoOfSubject = dr.Subjects.Count()
                                       })
                         .ToList();

你试过这个吗:

var count = context.Students.Select(x=>new { Name = x.Student.FirstName, 
    NoOfSubject = x.Subjects.SubjectId.Count}).ToList();