简体   繁体   中英

Converting from IQueryable to IEnumerable

How do I convert from IQueryable to IEnumerable ? I looked at another post Get from IQueryable to IEnumerable but it's not generic enough to reuse? Can anyone provides a generic reusable way to do this?

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

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

        return list;
    }
}

Error message:

Cannot implictly converty type 'System.Linq.IQueryable<Dashboard.EntityFramework.bit_sanity_results>' to 'System.Collections.IEnumerable<Dashboard.Model.ApiModels.BuildMetrics>' .An explicit conversion exists(are you missing a cast?)

Try converting queryable to enumerable with this:

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

This will give you an enumerable collection but I think you may have to generate BuildMetrics objects from bit_sanity_results that are returned by this. Like:

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

Example

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

Table from which we select:

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;
        }
    }
}

The conversion in this case should actually be implicit as IQueryable<T> implements IEnumerable<T> .

Your problem here is a type mismatch, as you are getting IQueryable<bit_sanity_results> but are trying to return IEnumerable<BuildMetrics> .

You'd need to project the IQueryable<bit_sanity_results> to IEnumerable<BuildMetrics> .

Something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM