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

C# 无法将System.Linq.IQueryable类型隐式转换为System Collections.Generic.IEnumerable,c#,linq,generics,C#,Linq,Generics,我有一个linq查询,它将选择表InventoryLocation中的所有记录。但是它给了我一个错误。。。我不知道是什么问题。。。我真的是个新手,所以请容忍我 错误 无法将类型System.Linq.IQueryable隐式转换为System Collections.Generic.IEnumerable 提前谢谢 public IEnumerable<InventoryLocationModel> GetInventoryLocations() { IEn

我有一个linq查询,它将选择表InventoryLocation中的所有记录。但是它给了我一个错误。。。我不知道是什么问题。。。我真的是个新手,所以请容忍我

错误

无法将类型System.Linq.IQueryable隐式转换为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;
    }
public IEnumerable GetInventoryLocations()
{
IEnumerable results=null;
使用(DataContext ctx=newdatacontext())
{
结果=从ctx中的a。库存位置选择a;
}
返回结果;
}

主要问题是您没有实际执行查询,因此只剩下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 GetInventoryLocations()
{
IEnumerable results=null;
使用(DataContext ctx=newdatacontext())
{
结果=(从ctx.InventoryLocations中的a中选择a).ToList();
}
返回结果;
}
您还可以简化查询。你真正需要做的就是

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

这将得到您想要的:

results = (from a in ctx.InventoryLocations select a).AsEnumerable();

这可以确保您仍然利用LINQ。

因此没有错误?。。。我只需要执行这个方法?不,有个错误。您正试图将
IQueryable
分配给
IEnumerable
,但这两种类型之间没有定义隐式转换,因此您会得到隐式强制转换编译器错误。要实际运行EF查询,您需要以某种方式实现数据。您将看到使用的主要工具有
ToList()
First()
FirstOrDefault()
Single()
,和
SingleOrDefault()
。还有其他方法,但根据我的经验,这些方法是最常用的。
ToList()
急切地执行查询,这可能不是我们想要的,特别是因为该方法正在返回
IEnumerable
。最好将执行延迟到调用链的更高层,由调用方决定。@ShiguriAnemone“很明显,您没有向我们展示完整的代码。
ToList
不可能导致相同的错误(将
IQueryable
转换为
inumerable
)。要么是您在其他位置收到错误,要么是您误解了Bradford的解决方案。@ShiguriAnemone“我在Visual Studio中复制了整个代码块,没有任何问题。”。你确定这个错误来自这个程序吗?是的,先生。。。这条线上还是有个错误。。。同样的error@ShiguriAnemone“那么,你没有告诉我们整个故事。Rex的答案中没有强制转换,因此我发现很难相信您会收到与无效强制转换相关的错误。请尝试:
results=(从ctx.InventoryLocations中的a中选择a)。AsEnumerable()您的
DataContext.InventoryLocations的返回类型是什么?