[英]Dynamic linq query for date comparison asp.net core
I have a simplified version of dynamic main query as follows:我有一个动态主查询的简化版本如下:
var items = context.itemsGalore.Where(where).ToList();
The where for the Where condition is built dynamically as below. Where 条件的 where 是动态构建的,如下所示。
if(compare == "Greater")
{
where = String.Format("{0} > {1}", DueDate, DateTime.ParseExact(dtValue.ToShortDateString(), "MM/dd/yyyy", CultureInfo.InvariantCulture));
}
else if(compare == "Lesser")
{
where = String.Format("{0} < {1}", field, DateTime.ParseExact(dtValue.ToShortDateString(), "MM/dd/yyyy", CultureInfo.InvariantCulture));
}
However I am getting the following error: Operator '<' incompatible with operand types 'DateTime' and 'Int32'但是我收到以下错误:运算符“<”与操作数类型“DateTime”和“Int32”不兼容
How do I go about fixing the issue?我如何解决问题 go?
in the code this section:在本节代码中:
else if(compare == "Lesser")
{
where = String.Format("{0} < {1}", field, DateTime.ParseExact(dtValue.ToShortDateString(), "MM/dd/yyyy", CultureInfo.InvariantCulture));
}
The Error is because of the data type of variable 'field' that is not DateTime.错误是因为变量“field”的数据类型不是 DateTime。
for example run this code:例如运行这段代码:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
var compare = "Lesser";
var where = "";
var DueDate = DateTime.Now;
var dtValue = DateTime.Now;
var field = 1;
if(compare == "Greater")
{
where = String.Format("{0} > {1}", DueDate, DateTime.ParseExact(dtValue.ToShortDateString(), "MM/dd/yyyy", CultureInfo.InvariantCulture));
}
else if(compare == "Lesser")
{
where = String.Format("{0} < {1}", field, DateTime.ParseExact(dtValue.ToShortDateString(), "MM/dd/yyyy", CultureInfo.InvariantCulture));
}
Console.WriteLine(where);
}
}
the output is something like this: "1 < 10/07/2021 00:00:00" and you can not use this as a where clause. output 是这样的:“1 < 10/07/2021 00:00:00”,您不能将其用作 where 子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.