将DbFunctions方法与匿名类型New Expression一起使用

时间:2018-12-25 12:46:32

标签: c# entity-framework lambda expression-trees

我需要构建一个表达式:

{
   t => new {
        field1 = t.field1,
        field2 = t.field2,
        dateTimeField = TruncateTime(t.dateTimeField)
     }
}

我已经构建了表达式:

{
     t => new {
         field1 = t.field1,
         field2 = t.field2,
         dateTimeField = t.dateTimeField
       }
 }

使用LatticeUtilsAnonymousTypes,但是我无法使用t.dateTimeField函数包装TruncateTime

这是我的代码:

    public static Expression<Func<T, dynamic>> GroupByExpressionAnonymous(string fields,
        string groupByDateField = null)
    {

        ISet<string> propertyNames = new HashSet<string>(fields.Split(',').Select(t => t.Trim()).ToList());

        if (!String.IsNullOrEmpty(groupByDateField))
        {
            propertyNames.Add(groupByDateField);
        }

        ParameterExpression entityParameterExpression = Expression.Parameter(typeof(T), @"t");

        var properties = typeof(T).GetProperties().Where(p => propertyNames.Contains(p.Name));

        var propertyExpressions = properties.Select(p => Expression.Property(entityParameterExpression, p));

        var anonymousType = AnonymousTypeUtils.CreateType(properties.ToDictionary(p => p.Name, p => p.PropertyType));
        var anonymousTypeConstructor = anonymousType.GetConstructors().Single();
        var anonymousTypeMembers = anonymousType.GetProperties().Cast<MemberInfo>().ToArray();

        var anonymousTypeNewExpression = Expression.New(anonymousTypeConstructor, propertyExpressions, anonymousTypeMembers);

        return Expression.Lambda<Func<T, dynamic>>(anonymousTypeNewExpression, entityParameterExpression);
    }

在这种情况下,如何使用DbFunction截断到表达式字段之一?

0 个答案:

没有答案