LINQ查询列表中的列表
我有这种情况:
我的ModelView:
public class Subject { public int ID { get; set; } public string Name { get; set; } public int ProfessorID { get; set; } public string ProfessorFullName{ get; set; } public IList Assistants { get; set; } } public class Assistant { public string AssistantFullName{ get; set; } }
我的查询:
var subjects = from subject in Entities.Subjects from professor in subject.Lecturers where professor.Professor == true select new SSVN.ModelView.Subject() { ID = subject.ID, Name= subject.Name, ProfessorFullName= professor.LastName+ " " + professor.Name, Assistants= (from subject1 in Entities.Subjects from assistant in subject1.Lecturers where assistant.Professor == false select new SSVN.ModelView.Assistant() { AssistantFullName = assistant.LastName+ " " + assistant.Name }).ToList() };
当我打电话时:
subjects.ToList();
我得到例外:
LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[SSVN.ModelView.Assistant] ToList[Assistant] (System.Collections.Generic.IEnumerable`1[SSVN.ModelView.Assistant])' method, and this method cannot be translated into a store expression.
您无法在linq-to-entities查询中调用ToList
。 Linq-to-entities查询将始终投影到IEnumerable
因此如果您想要IList
,则必须在linq-to-objects中调用它。
试试这个:
var subjects = (from subject in Entities.Subjects from professor in subject.Lecturers where professor.Professor == true select new { ID = subject.ID, Name= subject.Name, ProfessorFullName= professor.LastName+ " " + professor.Name, Assistants= (from subject1 in Entities.Subjects from assistant in subject1.Lecturers where assistant.Professor == false select new SSVN.ModelView.Assistant() { AssistantFullName = assistant.LastName+ " " + assistant.Name }) }).AsEnumerable().Select(x => new SSVN.ModelView.Subject { ID = x.ID, Name = x.Name, ProfessorFullName = X.ProffesorFullName, Assistants = x.Assistants.ToList() });
您不能也不应该在IQueryablle查询中使用ToList()
。 请注意,此查询必须转换为SQL。
- 在隔离存储中绑定图像
- 如何将我的属性添加到代码生成的Linq2Sql类属性?
- C#.Net Serial DataReceived对于高速率数据,事件响应太慢
- 使用DataContractSerializer进行自定义序列化
- 从Cloud Service中的Azure文件访问装载
- 反序列化会导致List-Entries的副本
- T4 – > C#class to Knockout View Model in Typescript
- Java ExecutorService.newSingleThreadExecutor()的C#等价物,或者:如何序列化对资源的multithreading访问
- C#Web API基于GET请求的XML或JSON