繁体   English   中英

使用动态表达式的组的IQueryable LINQ转换错误

[英]IQueryable LINQ cast error for group by using dynamic expression

我先使用C#、. Net 4.5,MVC,实体框架5.0和代码。 我在使用devexpress的示例之一时遇到错误。 问题在于获取groupby值和聚合(计数)查询的列表。

该错误是无法将类型'System.Int32'强制转换为类型'System.Object'。 LINQ to Entities仅支持大小写EDM基本或枚举类型

实体/表是

public class Test
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime SubmitDate { get; set; }
    public int TotalValue { get; set; }
}

有关获取分组信息的测试代码

public void GetGroupInfo() 
{
    GetGroupInfo(Context.Tests, "TotalValue");
    GetGroupInfo(Context.Tests, "Name");
}

public static void GetGroupInfo(this IQueryable query, string fieldName)
{
    CriteriaToExpressionConverter converter = new CriteriaToExpressionConverter();

    var rowType = query.ElementType;
    query = query.MakeGroupBy(converter, new OperandProperty(fieldName));
    query = query.MakeOrderBy(converter, new ServerModeOrderDescriptor(new OperandProperty("Key"), false));

    /*
      i think the problem is from here
    */
    query = ApplyExpression(query, rowType, "Key", "Count");

    // ignore the GridViewGroupInfo, just a class to store the value
    var list = new List<GridViewGroupInfo>();
    foreach (var item in query)
    {
        var obj = (object[])item;
        list.Add(new GridViewGroupInfo() {KeyValue=obj[0], DataRowCount =(int)obj[1]});
    }
}

static IQueryable ApplyExpression(IQueryable query, Type rowType, params string[] names)   
{
    var parameter = Expression.Parameter(query.ElementType, string.Empty);
    var expressions = names.Select(n => query.GetExpression(n, rowType, parameter));
    var arrayExpressions = Expression.NewArrayInit(
        typeof(object),
        expressions.Select(expr=>Expression.Convert(expr,typeof(object))).ToArray()
    );
    var lambda = Expression.Lambda(arrayExpressions, parameter);

    var expression = Expression.Call(
        typeof(Queryable),
        "Select",
        new Type[] { query.ElementType, lambda.Body.Type },
        query.Expression,
        Expression.Quote(lambda)
    );
    return query.Provider.CreateQuery(expression);
}

static Expression GetExpression(this IQueryable query, string commandName, Type rowType,    ParameterExpression parameter)
{
    switch (commandName)
    {
        case "Key":
            return Expression.Property(parameter, "Key");
        case "Count":
            return Expression.Call(typeof(Enumerable), "Count", new Type[] { rowType }, parameter);
    }
    return null;
}

无论分组是在“名称”(字符串)类型还是“ TotalValue”(整数)类型上,它都给我错误。 有人可以帮忙吗? 感谢是否有人告诉我原因,原因和方式,因为我仍在学习整个.net,mvc和linq。

我确认您要执行的操作是这样的:

Context.Tests.GroupBy(t => t.TotalValue).Select(g => new { Key = g.Key, Count = g.Count() });
Context.Tests.GroupBy(t => t.Name).Select(g => new { Key = g.Key, Count = g.Count() });

但是使用手动创建的Expressions

您实际创建的以及问题所在是最后的选择:

 var arrayExpressions = Expression.NewArrayInit(
    typeof(object),
    expressions.Select(expr=>Expression.Convert(expr,typeof(object))).ToArray()
);

将为您提供相当于:

Select(g => new object[] { (object)g.Key, (object)g.Count() });

确实,尝试执行这样的查询将导致LINQ to Entities(就此而言,也是Entity Framework)抱怨它无法进行object

它可以处理的是转换为string 所以:

Select(g => new string[] { g.Key.ToString(), g.Count().ToString() });

几乎可以,但是现在数组初始化程序存在问题: “无法在查询结果中初始化数组类型'System.String []'。请考虑使用'System.Collections.Generic.List`1 [System.String ]”。 这很容易:

Select(g => new List<string> { g.Key.ToString(), g.Count().ToString() });

现在可以将其转换为SQL(至少是通过Entity Framework,但我想Linq to SQL也可以处理)。 因此,您应该使用以下arrayExpressions替换arrayExpressions

var arrayExpressions = Expression.ListInit(Expression.New(typeof(List<string>)),
                expressions.Select(expr => Expression.Call(expr, "ToString", null)).ToArray()
            );

现在就可以了。

总而言之,这是一种构建Linq查询的相当复杂的方法,很难调试,甚至更难阅读。 考虑使用通用类型IQueryable并编写lambda-这是Linq首先设计的目的。 如果您有或想要坚持使用手动表达式,我建议您先编写一个Linq查询(可能针对更具体的情况),分析它生成的表达式,然后尝试手动创建此表达式。

另外,将该表达式生成的SQL查询与应该执行相同工作的简单linq查询进行比较-第一个查询将更加复杂。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM