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。