So I'm trying to create an Expression That does a DateTime Compare on the Day of a Paticular date specified through an expression. However I keep getting the Error LINQ to Entities does not recognize the method 'get_Day()' method.
Get Day However is a able to be used with Entity Framework you can access the property and compare it fine if you build the lamba normally.
Normally It would complied down to sql something like
WHERE ((DATEPART (day, [Project6].[C1])) >= (DATEPART (day, '4/28/2015 12:00:00 AM')))
This is my function Does anyone know what I can do to fix this error?
public IQueryable<T> SetDateCompare<T>(IQueryable<T> OriginalQuery, Expression<Func<T, DateTime>> getDateFunc, DateTime ComparisonDate, bool isGreaterThan = true)
where T : class
{
if (isGreaterThan)
{
Expression left = Expression.Call(getDateFunc.Body, typeof(DateTime).GetMethod("get_Day"));
Expression right = Expression.Constant(ComparisonDate.Day, typeof(int));
Expression res = Expression.GreaterThan(left, right);
var whereCallLambda = Expression.Lambda<Func<T, bool>>(Expression.GreaterThanOrEqual(left, right), getDateFunc.Parameters.Single());
MethodCallExpression whereCall = Expression.Call(typeof(Queryable),
"Where",
new Type[] { OriginalQuery.ElementType },
OriginalQuery.Expression,
whereCallLambda);
OriginalQuery = OriginalQuery.Provider.CreateQuery<T>(whereCall);
}
return OriginalQuery;
}
You probably want to use SqlFunctions.DatePart
- that's basically the way of creating a query using DATEPART
in the SQL.
See more on this question at Stackoverflow