我正在使用动态 linq 库构建动态查询构建器。到目前为止,它适用于布尔、数字和文本,但不适用于日期。
我想知道日期的格式应该是什么才能正常工作。
这是执行 sb.ToString 返回的代码。
private string BuildQuery()
{
var sb = new StringBuilder();
//var list = RequestBaseBL.GetRequestByCustomQuery("RequestNumber == \"12\"");
#region 1st ROW of the QUERY
if (ColumnType(DdlColumn1.SelectedValue) == "Text")
{
if(DdlOperator1.SelectedValue == "==")
{
sb.Append(DdlColumn1.SelectedValue);
sb.Append(DdlOperator1.SelectedValue);
sb.Append("\"" + TxtValue1.Text + "\"");
}
if (DdlOperator1.SelectedValue == "<>")
{
sb.Append(DdlColumn1.SelectedValue);
sb.Append(DdlOperator1.SelectedValue);
sb.Append("\"" + TxtValue1.Text + "\"");
}
if (DdlOperator1.SelectedValue == "LIKE")
{
sb.Append(string.Format("{0}.Contains(\"{1}\")", DdlColumn1.SelectedValue, TxtValue1.Text));
}
if (DdlOperator1.SelectedValue == "NOT LIKE")
{
sb.Append(string.Format("!{0}.Contains(\"{1}\")", DdlColumn1.SelectedValue, TxtValue1.Text));
}
}
if (ColumnType(DdlColumn1.SelectedValue) == "Number")
{
sb.Append(DdlColumn1.SelectedValue);
sb.Append(DdlOperator1.SelectedValue);
sb.Append(TxtValue1.Text);
}
if (ColumnType(DdlColumn1.SelectedValue) == "Date")
{
sb.Append(DdlColumn1.SelectedValue);
sb.Append(DdlOperator1.SelectedValue);
sb.Append(TxtValue1.Text);
}
if (ColumnType(DdlColumn1.SelectedValue) == "Bool")
{
sb.Append(DdlColumn1.SelectedValue);
sb.Append(DdlOperator1.SelectedValue);
sb.Append(TxtValue1.Text);
}
#endregion
return sb.ToString();
}
string strSql = BuildQuery();
try
{
var list = RequestBaseBL.GetRequestByCustomQuery(strSql, DdlRequestType.SelectedValue).ToList();
private static void AddDateOperatorsToList(Dictionary<string, string> operators)
{
operators.Add("=", "Equals");
operators.Add("<>", "Not Equals");
operators.Add(">", "Greater than");
operators.Add(">=", "Greater or equal than");
operators.Add("<", "Less than");
operators.Add("<=", "Less or equal than");
}
更新1:
错误是:运算符 '=' 与操作数类型 'DateTime' 和 'Int32' 不兼容
sb.toString()
? sb.ToString() "RequestDate=12/12/2015"
更新 2:
更新 2 的错误:
“日期时间”类型中不存在适用的方法“解析”
if (ColumnType(DdlColumn1.SelectedValue) == "Date")
{
sb.AppendFormat("DateTime.Parse({0})", DdlColumn1.SelectedValue);
var str = string.Format("{0} {1} {2}", DdlColumn1.SelectedValue, DdlOperator1.SelectedValue,
DateTime.Parse(TxtValue1.Text));
//sb.Append(DdlColumn1.SelectedValue);
//sb.Append(DdlOperator1.SelectedValue);
//sb.Append(TxtValue1.Text);
sb.Append(str);
}
更新 3:
也没有工作
if (ColumnType(DdlColumn1.SelectedValue) == "Date")
{
var date = DateTime.Parse(TxtValue1.Text);
sb.Append(DdlColumn1.SelectedValue);
sb.Append(DdlOperator1.SelectedValue);
sb.Append("\"" + date.ToUniversalTime() + "\"");
//sb.Append(date.ToUniversalTime());
}