无法隐式转换类型 System.Linq.IQueryable 到 System.Collections.Generic.IEnumerable。

3
我有一个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;
    }

尝试:results = (from a in ctx.InventoryLocations select a).AsEnumerable<InventoryLocationModel>(); - Mark C.
你的 DataContext.InventoryLocations 的返回类型是什么? - jdphenix
2个回答

2

主要问题在于您实际上并没有执行查询,因此您只剩下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();
    }
}

所以没有错误?我只需要执行这个方法吗? - Sam Teng Wong
不行,有个错误。你正在尝试将IQueryable分配给IEnumerable,但是这两种类型之间没有隐式转换定义,因此你会得到一个隐式转换编译器错误。 - Bradford Dillon
为了使EF查询实际运行,您需要以某种方式实现 数据。您将看到使用的主要方法是 ToList()First()FirstOrDefault()Single()SingleOrDefault()。还有其他方法,但在我的经验中,这些是最常用的。 - Bradford Dillon
ToList() 方法会立即执行查询,这可能不是期望的行为,特别是当该方法返回 IEnumerable 时。最好将执行推迟到调用链的更高层,并让调用者决定。 - Rex M
@ShiguriAnemone,很明显你没有展示完整的代码。ToList不可能导致相同的错误(将IQueryable转换为IEnumerable)。要么你在不同的位置得到了错误,要么你误解了Bradford的解决方案。 - Rob

2
这将得到你想要的内容:
results = (from a in ctx.InventoryLocations select a).AsEnumerable();

这样可以确保您仍然可以利用LINQ的延迟执行


@ShiguriAnemone',我已经在Visual Studio中完整复制了代码块,没有任何问题。你确定错误是来自这个例程吗? - Rex M
是的先生...它仍然在这一行上出现错误...同样的错误。 - Sam Teng Wong
@ShiguriAnemone,你没有告诉我们完整的故事。Rex的回答中没有转换,所以我很难相信你遇到了与无效转换相关的错误。 - Rob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接