如何在动态linq中格式化日期文字?

Val*_*l M 4 c# linq datetime dynamic

我使用动态Linq返回用户输入搜索条件的数据.除了用户选择的日期之外,我的查询工作正常.我目前的代码是:

        StringBuilder whereClause = new StringBuilder();

        if (startDate.HasValue || endDate.HasValue)
        {
            DateTime searchStartDate = startDate.HasValue ? startDate.Value : DateTime.MinValue;
            DateTime searchEndDate = endDate.HasValue ? endDate.Value : DateTime.MaxValue;

            whereClause.AppendFormat("Date >= {0} && Date <= {1}",
                searchStartDate.Date.ToUniversalTime(),
                searchEndDate.Date.ToUniversalTime());
        }

        if (whereClause.Length > 0)
        {
            return (from p in this.repository.GetQueryable<Party>() select p)
                .Where(whereClause.ToString())
                .ToList();
        }
Run Code Online (Sandbox Code Playgroud)

查询失败,因为在DateTime字段和Int32字段之间进行比较,这意味着查询已将我的日期文字解释为整数.

我该如何格式化日期?

Axe*_*ger 8

使用

.Where("Date >= @0 && Date <= @1",
                searchStartDate.Date.ToUniversalTime(),
                searchEndDate.Date.ToUniversalTime())
Run Code Online (Sandbox Code Playgroud)

代替.

回答Val的评论:

好的,那么你可以这样做:

whereClause.AppendFormat("Date.ToString() >= \"{0}\" && Date.ToString() <= \"{1}\"",
                searchStartDate.Date.ToUniversalTime(),
                searchEndDate.Date.ToUniversalTime());
Run Code Online (Sandbox Code Playgroud)

您必须将查询中的日期转换为字符串,然后将其与带引号的字符串文字进行比较.如果没有引号,解析器就会将插入到where子句中的数字作为整数进行排序 - 这应该解释您最初得到的错误.