从动态 LINQ 表达式中的日期时间字段中排除时间比较

Exclude time comparison from Datetime field in Dynamic LINQ Expressions

我想生成动态 LINQ 表达式以仅使用日期进行过滤,但我的列是数据库中的日期时间字段。因此,运算符“等于”和“不等于”不起作用,因为它在我的输入中附加了一些默认时间并试图与数据匹配。如果有任何方法可以生成一个 LINQ 表达式,该表达式将通过排除时间来仅比较日期。

这是我的代码:

// for type conversion start
var propertyType = ((PropertyInfo)propertyName.Member).PropertyType;
var converter = TypeDescriptor.GetConverter(propertyType);

if (!converter.CanConvertFrom(typeof(string)))
     throw new NotSupportedException();

var propertyValue = ReturnPropertyValue(rule, converter);
var constant = Expression.Constant(propertyValue);
var valueExpression = Expression.Convert(constant, propertyType); //{Convert(5/24/2021 12:00:00 AM, DateTime)}
// for type conversion ends

// returning the expression
return Expression.Equal(propertyName, valueExpression);     
// {(Param_0.CreatedDate == Convert(5/24/2021 12:00:00 AM, DateTime))}

但是我需要这样的东西

{(Param_0.CreatedDate == Convert(5/24/2021 12:00:00 AM, Date))}

这将排除本次检查并仅与日期进行比较

不要这样做;走建议的路线,改用日期范围

始终设法避免在比较完成之前创建操纵 table 数据的查询。假设您有一个包含一千万个日期时间的 table,并且它们都已编入索引

数据库可能为此使用索引:

WHERE datecol >= '2001-01-01' and datecol < '2001-01-02'

数据库可能不会为此使用索引:

WHERE CAST(datecol as DATE) = '2001-01-01' 

.. 所以 每次查询 数据库将完全扫描 table 或索引,在进行比较之前转换所有一千万个值中的每一个

您可以在 C# linq 中尝试以下代码:-

var data = collection.Where(t=> DbFunctions.TruncateTime(t.CreatedDate)==DbFunctions.TruncateTime(dateVariable)).ToList();

以上代码将在 Linq 中进行字段比较时排除时间。