我首先使用 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;
}
无论分组是在“Name”(字符串)类型还是“TotalValue”(int)类型上,它都会给我错误。任何人都可以帮忙吗?感谢有人告诉我为什么,什么以及如何,因为我仍在学习整个 .net、mvc 和 linq。