【问题标题】:Cannot implicitly convert type System.Collections.Generic.List<IEnumerable> to <IEnumerable无法将类型 System.Collections.Generic.List<IEnumerable> 隐式转换为 <IEnumerable
【发布时间】:2016-06-09 14:41:37
【问题描述】:

我有两个类 Employee 和 Territory:

public class Territory
{        
    public string TerritoryID { get; set; }
    public string TerritoryDescription { get; set; }       
    public IEnumerable<Employee> Employees { get; set; }
}

我正在尝试使用 LINQ 按 TerritoryID 提取员工并获得异常:

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

例外是:

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

【问题讨论】:

    标签: c# asp.net-mvc entity-framework linq


    【解决方案1】:

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

    您在此处使用 Select() 所做的是创建一个包含所有员工集合的新 Enumerable。

    SelectMany 将所有“子”集合展平,并将每个员工聚合到单个 Enumerable 中。


    对于 cmets 中描述的第二个问题,Employees 似乎在表架构中或作为导航属性不为人所知。

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

    这是基于这个SO Post

    【讨论】:

    • 太棒了!使用 SelectMany() 消除了编译错误,现在在运行时我得到“LINQ to Entities 不支持指定的类型成员 'Employees'。仅支持初始化程序、实体成员和实体导航属性。”
    • 您的 Context 类中有员工 DBSet 吗?
    • 如果不是,您可能需要在SelectMany 之前添加.Include(t =&gt; t.Employees)
    • @Gaurav 如果您的目标是获取 IEnumerable 而不是 List 集合,只需将扩展名更改为“ToArray()”即可。 EG(我的代码中有类似的东西) IEnumerable orders = context.tePersons.SelectMany(x => x.teOrders).ToArray();
    • @Botonomous,是的,我在 Context 类中有员工 DBSet。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多