c# - 无法将类型 System.Linq.IQueryable 隐式转换为 System Collections.Generic.IEnumerable

标签 c# linq generics

我有这个 linq 查询,它将选择我的表 InventoryLocation 中的所有记录。但是它给了我一个错误...我不知道是什么问题...我真的很陌生所以请耐心等待...

错误

Cannot implicitly convert type System.Linq.IQueryable to System Collections.Generic.IEnumerable

提前致谢..

 public IEnumerable<InventoryLocationModel> GetInventoryLocations()
    {
        IEnumerable<InventoryLocationModel> results = null;

        using (DataContext ctx = new DataContext())
        {
            results = from a in ctx.InventoryLocations select a;
        }

        return results;
    }

最佳答案

主要问题是您实际上并没有执行查询,因此您只剩下 IQueryable 而不是实际结果,因此您收到了错误。

public IEnumerable<InventoryLocationModel> GetInventoryLocations()
{
    IEnumerable<InventoryLocationModel> results = null;

    using (DataContext ctx = new DataContext())
    {
        results = (from a in ctx.InventoryLocations select a).ToList();
    }

    return results;
}

您还可以简化查询。您真正需要做的就是

public IEnumerable<InventoryLocationModel> GetInventoryLocations()
{
    using (DataContext ctx = new DataContext())
    {
        return ctx.InventoryLocations.ToList();
    }
}

关于c# - 无法将类型 System.Linq.IQueryable 隐式转换为 System Collections.Generic.IEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33381789/

相关文章:

C#匿名类型从其他方法访问

c# - Linq thenBy() 抛出 "The best overloaded method match ThenBy() for has some invalid arguments"异常

java - Java8 中不合逻辑的类型推断

java - 如何向参数化方法提供参数,直到运行时我才知道其类型?

c# - C# 中的冗余?

c# - 调试版本中带有垃圾收集的奇怪触发的奇怪错误

C# 控制台应用程序 : reference file without . .\..\文件名

c# - 如何将 LINQ group 和 ordering 与父表和子表结合起来?

c# - ASP.NET 路由和 CMS

c# - 无法安装 NuGet 包 : Falling back to NuGet Local Cache