从IQueryable转换为IEnumerable

时间:2017-02-28 01:31:40

标签: c#

如何从IQueryable转换为IEnumerable?我查看了另一篇帖子Get from IQueryable to IEnumerable,但它不够通用,无法重复使用?任何人都可以提供通用的可重用方法吗?

public class SoftwareProductRepository
{
    BitDatabaseEntities bitDB = new BitDatabaseEntities();
    public IEnumerable<BuildMetrics> GetBuildMetrics()
    {

        var list = (from r in bitDB.bit_sanity_results select r);

        return list;
    }
}

错误讯息:

  

无法隐含转换类型   'System.Linq.IQueryable<Dashboard.EntityFramework.bit_sanity_results>'   至   'System.Collections.IEnumerable<Dashboard.Model.ApiModels.BuildMetrics>'。一种   存在显式转换(您是否错过了演员?)

2 个答案:

答案 0 :(得分:3)

尝试使用以下方法将queryable转换为enumerable:

(from r in bitDB.bit_sanity_results select r).AsEnumerable();

这将为您提供一个可枚举的集合,但我认为您可能必须从BuildMetrics生成由此返回的bit_sanity_results个对象。像:

(from r in bitDB.bit_sanity_results select new BuildMetrics{
       <some BuildMetrics property>=r.<some bit_sanity_results property>
        }).AsEnumerable();

示例

public class ReturnClass
{
    public string SSId{get;set;}
    public string Name{get;set;}
}

我们从中选择的表:

table values_store
(
    ss_id varchar(50),
    user_name varchar(250)
)

public class ReturnValuesRepository
{
    public IEnumerable<ReturnClass> GetReturnClasses()
    {   
        //As commented by @Enigmativity if your `BitDatabaseEntities` is `IDisposable` (sure if it inherits from `DbContext`) you should wrap it in a `using` block
        using(var db = new ValuesEntities())
        {
            var list = (from r in db.values_store select new 
                   ReturnClass
                     {
                         SSId=r.ss_id,
                         Name=r.user_name
                    }).AsEnumerable();

            return list;
        }
    }
}

答案 1 :(得分:1)

在这种情况下,转换实际上应该隐含为IQueryable<T> implements IEnumerable<T>

您的问题是类型不匹配,因为您收到IQueryable<bit_sanity_results>但正在尝试返回IEnumerable<BuildMetrics>

您需要将IQueryable<bit_sanity_results>投射到IEnumerable<BuildMetrics>

这样的事情:

public class SoftwareProductRepository
{
    BitDatabaseEntities bitDB = new BitDatabaseEntities();
    public IEnumerable<BuildMetrics> GetBuildMetrics()
    {
        return bitDB.bit_sanity_results.Select(r => new BuildMetrics(...));
    }
}