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
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
Try the below code.
return db.Approved.Where(predicate).Select(x =>new {x.RefNo, x.RefGroup, x.Location });
As it create the anonymous object.
精彩评论