无法将类型System.Collections.Generic.List <IEnumerable>隐式转换为<IEnumerable

Kum*_*rav 1 c# linq asp.net-mvc entity-framework

我有两个类Employee和Territory:

public class Territory
{        
    public string TerritoryID { get; set; }
    public string TerritoryDescription { get; set; }       
    public IEnumerable<Employee> Employees { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我试图使用LINQ通过TerritoryID拉出Employees并获得异常:

IEnumerable<Employee> empList = context.Territories
  .Where(x => x.TerritoryID == territoryID)
  .Select(y => y.Employees)
  .ToList();
Run Code Online (Sandbox Code Playgroud)

例外情况是:

无法将System.Collections.Generic.List <System.Collections.Generic.IEnumerable <Employee >>类型隐式转换为System.Collections.Generic.IEnumerable <Employee>.存在显式转换.

Sid*_*r94 5

您需要使用该SelectMany()方法而不是Select()

你在这里做的Select()是创建一个包含所有Employees Collections的新Enumerable.

SelectMany 扁平化所有"子"集合并将每个员工聚合成一个Enumerable.


对于注释中描述的第二个问题,似乎Employees在表模式中或作为导航属性未知.

一种解决方法是在调用ToList()之前SelectMany()调用以确保执行SQL查询并在内存中执行其余操作.

这是基于这个SO帖子