3

使用时:

DateTime.ToString().Contains("2016")

实体框架产生:

CAST(DateValue AS nvarchar(max)) LIKE '%2016%'

这使用默认日期格式“mon dd yyyy hh:miAM (or PM)”

我想用户“yyyy-mm-dd hh:mi:ss (24h)”可以通过以下方式获得:

CONVERT(VARCHAR(max), DateValue, 20) LIKE '%2016%'

我需要帮助将这种格式应用于现有的通用方法。

static Expression<Func<T, TResult>> Expr<T, TResult>(Expression<Func<T, TResult>> source) { return source; }
static MethodInfo GetMethod(this LambdaExpression source) { return ((MethodCallExpression)source.Body).Method; }
static readonly MethodInfo Object_ToString = Expr((object x) => x.ToString()).GetMethod();
static readonly MethodInfo String_Contains = Expr((string x) => x.Contains("y")).GetMethod();

public static IQueryable<T> Filter<T>(this IQueryable<T> query, List<SearchFilterDto> filters)
 where T : BaseEntity
{
    if (filters != null && filters.Count > 0 && !filters.Any(f => string.IsNullOrEmpty(f.Filter)))
    {
        var item = Expression.Parameter(query.ElementType, "item");
        var body = filters.Select(f =>
        {
            var value = f.Column.Split('.').Aggregate((Expression)item, Expression.PropertyOrField);
            if (value.Type != typeof(string))
            {
                value = Expression.Call(value, Object_ToString);
            }

            return (Expression)Expression.Call(value, String_Contains, Expression.Constant(f.Filter));
        })
        .Where(r => r != null)
        .Aggregate(Expression.AndAlso);

        var predicate = Expression.Lambda(body, item);
        MethodInfo whereCall = (typeof(Queryable).GetMethods().First(mi => mi.Name == "Where" && mi.GetParameters().Length == 2).MakeGenericMethod(query.ElementType));
        MethodCallExpression call = Expression.Call(whereCall, new Expression[] { query.Expression, predicate });
        query = query.Provider.CreateQuery<T>(call);
    }
    return query;
}

请注意,这是一个示例 - 它并不总是“2016”,也不总是一年。用户可以键入时间或“01”来调用该月的第一天、1 月或 2001 年的所有记录。这是一个非常灵活的过滤器。

我也明白很多人不会喜欢这种情况,但我真的在这里寻找解决方案而不是被告知“不要这样做”

该解决方案还需要满足 LINQ to Entities,所以我不能简单地 .ToString("MMM d yyyy H:mm tt") 因为这将导致:

“LINQ to Entities 无法识别方法 'System.String ToString(System.String)' 方法,并且此方法无法转换为存储表达式。”

该代码使用默认的日期格式。我提出问题的原因是通过在实体框架中操作查询来更改 SQL 级别的日期格式。

4

2 回答 2

1

我发现产生所需结果的唯一方法是使用这样的表达式手动构建它

Expression<Func<DateTime, string>> Date_ToString = date =>
    DbFunctions.Right("000" + date.Year.ToString(), 4) + "-" +
    DbFunctions.Right("0" + date.Month.ToString(), 2) + "-" +
    DbFunctions.Right("0" + date.Day.ToString(), 2) + " " +
    DbFunctions.Right("0" + date.Hour.ToString(), 2) + ":" +
    DbFunctions.Right("0" + date.Minute.ToString(), 2) + ":" +
    DbFunctions.Right("0" + date.Second.ToString(), 2);

丑陋,我知道。坦率地说,您不想从上面的表达式中看到 EF 生成的 SQL - 与期望相比是一个巨大的怪物CONVERT(...)。但至少它有效。

这是代码。可以使用 构建上述表达式System.Linq.Expressions,但我对此太懒了,并使用了一个简单的参数替换器。

修改部分:

if (value.Type != typeof(string))
{
    if (value.Type == typeof(DateTime))
        value = value.ToDateString();
    else if (value.Type == typeof(DateTime?))
        value = Expression.Condition(
            Expression.NotEqual(value, Expression.Constant(null, typeof(DateTime?))),
            Expression.Property(value, "Value").ToDateString(),
            Expression.Constant(""));
    else
        value = Expression.Call(value, Object_ToString);
}

和使用的助手:

static readonly Expression<Func<DateTime, string>> Date_ToString = date =>
    DbFunctions.Right("000" + date.Year.ToString(), 4) + "-" +
    DbFunctions.Right("0" + date.Month.ToString(), 2) + "-" +
    DbFunctions.Right("0" + date.Day.ToString(), 2) + " " +
    DbFunctions.Right("0" + date.Hour.ToString(), 2) + ":" +
    DbFunctions.Right("0" + date.Minute.ToString(), 2) + ":" +
    DbFunctions.Right("0" + date.Second.ToString(), 2);

static Expression ToDateString(this Expression source)
{
    return Date_ToString.ReplaceParameter(source);
}

static Expression ReplaceParameter(this LambdaExpression expression, Expression target)
{
    return new ParameterReplacer { Source = expression.Parameters[0], Target = target }.Visit(expression.Body);
}

class ParameterReplacer : ExpressionVisitor
{
    public ParameterExpression Source;
    public Expression Target;
    protected override Expression VisitParameter(ParameterExpression node)
    {
        return node == Source ? Target : base.VisitParameter(node);
    }
}
于 2016-02-14T00:36:39.830 回答
1

如果您试图从输入值确定日期是否在一年内,为什么不:

DateTime.Year == 2016 //or your variable

不过,也许您的需求比我看到的要多。

于 2016-02-13T20:59:11.843 回答