如何在运行时创建一个表达式,为在GROUPBY()与实体框架使用? [英] How to create an expression at runtime for use in GroupBy() with Entity Framework?
问题描述
我建立这将动态地能够从实体框架组查询结果的新的扩展方法。
I am building a new extension method which will dynamically be able to group query results from Entity Framework.
我已经能够建立动态,其中表达式中使用。LinqKit,但是这似乎是一个不同的动物
I have been able to build dynamic "where" expressions using LinqKit, but this seems to be a different animal.
新的扩展方法预期用法:
Intended usage of new extension method:
var results = entities.GroupBy("someFieldName").ToList();
扩展方法定义:
Extension method definition:
public static IQueryable<IGrouping<object, TEntity>> GroupBy<TEntity>(
this IQueryable<TEntity> source,
string fieldName)
where TEntity : class, IDataEntity
{
if (string.IsNullOrEmpty(fieldName))
{
return new List<IGrouping<object, TEntity>>().AsQueryable();
}
var parameter = Expression.Parameter(typeof(TEntity), "x");
var fieldXExpression = Expression.Property(parameter, fieldName);
var lambda = Expression.Lambda<Func<TEntity, object>>(
Expression.Convert(fieldXExpression, typeof(object)), // throws error when using EF
parameter);
return source.AsExpandable().GroupBy(lambda);
}
我需要使用 Expression.Convert(.. 。)
,因为当我使用linqTOobjects测试,当列是代码失败 INT32
。所以,我需要手动转换列对象和它的工作太棒了。
I need to use Expression.Convert(...)
because when I was testing using linqTOobjects, the code failed when the column was a int32
. So I needed to manually convert the column to object and it worked great.
现在我正在使用EF实体测试它,我想这EF试图翻译。转换成等价的SQL,当然我知道不存在
Now that I'm testing it with EF entities, I guess that EF is trying to translate the convert to equivalent SQL, which of course I know doesn't exist.
错误:
System.NotSupportedException: Unable to cast the type 'System.String' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
有没有在运行时产生适合于GROUPBY表达的方式也与EF兼容?
Is there a way to generate an expression suitable for GroupBy at runtime that is also compatible with EF?
感谢您的任何指导。
推荐答案
我能够做到什么我需要通过使用动态的LINQ。我创建了一个扩展方法调用ListGroupKeys:
I was able to accomplish what I needed by using Dynamic Linq. I created an extension method called ListGroupKeys:
public static List<object> ListGroupKeys<TEntity>(this IQueryable<TEntity> source, string fieldName)
where TEntity : class, IDataEntity
{
var results = source.GroupBy(fieldName, "it").Select("new (KEY as Group)");
var list = new List<object>();
foreach (var result in results)
{
var type = result.GetType();
var prop = type.GetProperty("Group");
list.Add(prop.GetValue(result));
}
return list;
}
这让我拿到小组第一键值在后续查询使用。
This allowed me to get the group key values for use in subsequent queries.
这篇关于如何在运行时创建一个表达式,为在GROUPBY()与实体框架使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!