MrBliz
MrBliz

Reputation: 5918

returning multiple fields back from a Linq lambda

I have the following code which returns results back from a database where columnName = Y'. The code words fine until i want to limit what fields are returned by the query.

I get the error

Cannot implicitly convert type 'System.Linq.IQueryable[AnonymousType#1]' to 'System.Linq.IQueryable[MyApp.Models.Approved]'. An explicit conversion exists (are you missing a cast?)

public IQueryable<Approved> ReturnRecordsByObjectiveFlag(string columnName)
    {
        var param = Expression.Parameter(typeof(Approved), "x");
        var predicate = Expression.Lambda<Func<Approved, bool>>(
            Expression.Equal(
                Expression.PropertyOrField(param, columnName),
                Expression.Constant('Y',typeof(char?))
            ), param);
        return db.Approved.Where(predicate).Select(x =>new{x.RefNo, x.RefGroup, x.Location });
    }

it is on this line that i get the error

return db.Approved.Where(predicate).Select(x =>new{x.RefNo, x.RefGroup, x.Location });  

Whereabouts do i make the cast?

Many thanks to Marc Gravell for Answering an earlier question on this same method

Upvotes: 1

Views: 14730

Answers (2)

Jayesh Tanna
Jayesh Tanna

Reputation: 418

Try the below code.

return db.Approved.Where(predicate).Select(x =>new {x.RefNo, x.RefGroup, x.Location });  

As it create the anonymous object.

Upvotes: 1

Hakeem
Hakeem

Reputation: 346

This should work

return db.Approved.Where(predicate).Select(x =>new Approved{x.RefNo, x.RefGroup, x.Location });  

It gives that error because the select statement is creating an anonymous type

Upvotes: 6

Related Questions