Reputation: 822
I want to pass a lambda to my .Select() method depending on a condition.
I set my lambda up like this:
Func<Monthly, int?> f = x => x.CLDD;
I then set up my .Select() like this:
IQueryable query =
db.Monthlies
.GroupBy(o => o.Date.Value.Year)
.Select(
o => new {
Year = o.Key,
MaxDate = o.Max(x => x.Date),
Data = o.Sum(f)
}
)
.Where(o => o.Year != currentYear)
.OrderBy(o => o.Year);
The code compiles and runs fine but the query does not send back any results. When I debug and watch query I see it says:
+ base {"Internal .NET Framework Data Provider error 1025."}
System.SystemException {System.InvalidOperationException}
Note if instead I do:
Expression<Func<Monthly, int?>> f = x => x.CLDD;
Then o.Sum(f) errors saying:
Error 1 Instance argument: cannot convert from
'System.Linq.IGrouping<int,MyWeb.Models.Monthly>' to
System.Linq.IQueryable<MyWeb.Models.Monthly>'
Thank you!
Upvotes: 0
Views: 648
Reputation: 20194
You were close, Entity Framework needs an Expression
to work not Func
, but the Sum
extension method that receives an Expression
works only with IQueryable
.
Now inside Select
you are getting an IGrouping
from GroupBy
which does not implement IQueryable
only IEnumerable
.
So you just need to cast it to get the right extension method:
Data = o.AsQueryable().Sum(f)
Upvotes: 2