I have a generic class where I need to convert constructor parameters into DateTime?:
var startDate = CompareValueFirst == null ? (DateTime?)null : Convert.ToDateTime(CompareValueFirst);
var endDate = CompareValueSecond == null ? (DateTime?)null : Convert.ToDateTime(CompareValueSecond);
Then I make a Linq Expression like this:
var startDateRight = startDate != null ? Expression.Constant(new DateTime(startDate.Value.Year, startDate.Value.Month, startDate.Value.Day, 0, 0, 0), typeof(DateTime?)) : Expression.Constant(startDate);
var endDateRight = endDate != null ? Expression.Constant(new DateTime(endDate.Value.Year, endDate.Value.Month, endDate.Value.Day, 23, 59, 59), typeof(DateTime?)) : Expression.Constant(endDate);
(which is probably not yet the most optimized form of code, but that's not the point)
and on the basis of that datetimes I make an expression:
var parameter = Expression.Parameter(typeof(T), "x");
var left = propertyName.Split('.').Aggregate((Expression)parameter, Expression.Property);
var expression = Expression.AndAlso(
Expression.MakeBinary(ExpressionType.GreaterThanOrEqual, left, startDateRight),
Expression.MakeBinary(ExpressionType.LessThanOrEqual, left, endDateRight));
which finally is used for result expression creation:
Expression<Func<T, bool>> ExpressionResult;
ExpressionResult = Expression.Lambda<Func<T, bool>>(expression, parameter);
var results = list.Where(ExpressionResult);
on DB I get an error:
Conversion failed when converting date and/or time from character string.
because format of the resulting datetime in query is:
'2022-08-25T00:00:00.0000000'
but should be:
'2022-08-25 00:00:00'
Question: how to take control over that resulting datetime format and set it appropriately? (if some parts of code above are not consistent sorry for that, I have my code divided into many methods and had to glue it together into a more or less coherent whole)