Skip to main content
 首页 » 编程设计

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

2024年02月05日9www_RR

我有这个 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(); 
    } 
}