I have a query generator based on C# Expression Trees which I use it to feed the Where condition of a IQueryable<T> in EFCore 3.1. The mechanism is that it parses an object called FilterCriterion within which it included auto properties such as Field of type string, Value of type object, OperationExpression of type enum. In the last point of generating Expression object just before it is chained to Lambda<Func<T,bool>>, I have a method like this:
private static Expression GetConstantExpressionWithProperOperatorSpecified(
Type lastInnerType,
MemberExpression memberExpression,
object propertyValue,
OperationExpression operationToCheckWith)
{
Expression result = null;
MethodInfo contains = null;
switch (operationToCheckWith)
{
case OperationExpression.Equals:
if (TypeHelper.GetTypeAliasName(lastInnerType) == "DateTime" || TypeHelper.GetTypeAliasName(lastInnerType) == "DateTime?")
{
var dateTimeVariable = Expression.Variable(lastInnerType);
var res = Expression.Assign(dateTimeVariable, Expression.Constant(propertyValue, lastInnerType));
result = Expression.Equal(memberExpression, dateTimeVariable);
}
else
{
result = Expression.Equal(memberExpression, Expression.Constant(propertyValue, lastInnerType));
}
break;
}
And in the code which is the client of this method, when it reaches to the Count() method:
var dbSet = ((CRMNewDbContext)_orderDbContext).Orders;
IQueryable<Order> queryable = null;
var findCriteria = (OrderFindCriteria)orderFindCriteria;
queryable = ApplyIncludes(dbSet);
var filteredQueryable = ApplyCriteriaOnQueryable(queryable, findCriteria);
filteredQueryable = ApplySortCriteria(filteredQueryable, findCriteria.Sorts);
var total = filteredQueryable.Count();
it produces the error:
Value cannot be null. (Parameter 'key')'
I would hope that it worked just like when as regular we type the expression by hand in the code like this:
var rightVal = Convert.ToDateTime("2020-02-27");
orderQueryable = orderQueryable.Where(order =>
order.OrderDate == rightVal);
but it does not work.
What I have tried:
Try to convert and consider the date time as string.