C# 无法获取lambda表达式中的计数-NotSupportedException
我正在尝试使用以下查询获取每个学生的科目数:C# 无法获取lambda表达式中的计数-NotSupportedException,c#,entity-framework,lambda,notsupportedexception,C#,Entity Framework,Lambda,Notsupportedexception,我正在尝试使用以下查询获取每个学生的科目数: var selectedSubject = context.Students .Include(d => d.Subjects) .Select(dr => new {
var selectedSubject = context.Students
.Include(d => d.Subjects)
.Select(dr => new
{
Name = dr.Student.FirstName,
NoOfSubject = dr.Subjects.Count
})
.ToList();
但我有个例外
EntityFramework.SqlServer.dll中发生类型为“System.NotSupportedException”的未处理异常
其他信息:LINQ to实体中不支持指定的类型成员“Subjects”。仅支持初始值设定项、实体成员和实体导航属性
你试过这个吗:
var count = context.Students.Select(x=>new { Name = x.Student.FirstName,
NoOfSubject = x.Subjects.SubjectId.Count}).ToList();
在查询具体化之前,您将无法访问
IList
界面上的非实体成员
属性(如计数
)
要么提前实现:
var selectedSubject = context.Students
.Include(d => d.Subjects)
// .Where() goes here,
.ToList()
.Select(dr => new
{
Name = dr.Student.FirstName,
NoOfSubject = dr.Subjects.Count
})
.ToList();
或者,使用可映射到Sql的Count()
方法:
var selectedSubject = context.Students
.Include(d => d.Subjects)
.Select(dr => new
{
Name = dr.Student.FirstName,
NoOfSubject = dr.Subjects.Count()
})
.ToList();
您可以添加学生和科目模型的相关部分吗?我们需要查看您的模型定义。EF告诉您,
主题
不可查询。