2

我正在使用动态linq为适度复杂的搜索构建where子句,并且遇到了日期问题。之前和之后的日期时间比较

我希望用户能够在“创建日期”上筛选搜索任何在该日期之前,该日期或该日期之后的任何内容。

我发现this answer,我用它构造了一个如下所示的动态查询:.Year == @0.Year && created.Month == @0.Month && created.Day == @0.Day)"。这适用于搜索完全相同的日期,但在尝试搜索某些内容之前或之后时不会出现问题。我得到的最远距离是"(created.Year >= @0.Year && created.Month >= @0.Month && created.Day > @0.Day),它不适用于当前月份之外的任何事情(如果我搜索了(今天之后),即使它们在日期我搜索。)

我尝试使用DateTime.Compare以及但没有工作,也没有试图比较DateTime.Date`。

有什么办法可以直接使用T-SQL吗?

编辑:用"(created.Date == @0.Date)"

enter image description here

+2

为什么不简单'created.Date> @ yourDate.Date'或'created.Date <@ yourDate.Date'? (假设'created'和'@ yourDate'类型为'DateTime') – Corak

+0

因为Linq to Entities不支持那个... – Mansfield

+0

如果它支持'.Day','.Month'和“.Year”,但不是“.Date”。 – Corak

回答

0

我结束了使用我现有的“开”比较,只是做了严格的><之前和作为Corak建议后的代码。

if (Comparison == ComparisonType.Equals) { 
    return string.Format("({0}.Year {2} @{1}.Year && {0}.Month {2} @{1}.Month && {0}.Day {2} @{1}.Day)", FieldName, index, ComparisonType.Equals.Evaluate()); //workaround for "exactly equals date" 
} else if (Comparison == ComparisonType.Less_Than) { 
     Value = ((DateTime)Value).Minimize(); //set the time values of the date to the minimums (00:00:00 000) 
} else if (Comparison == ComparisonType.Greater_Than) { 
     Value = ((DateTime)Value).Maximize(); //set the time values of the date to the maximums (23:59:59 999) 
} 

return string.Format("({0} {1} @{2})", FieldName, Comparison.Evaluate(), index); 
相关问题