我正在構建一個新的擴展方法,它將動態地將來自實體框架的查詢結果分組。如何在運行時創建表達式以用於GroupBy()和Entity Framework?
我已經能夠使用LinqKit構建動態的「where」表達式,但這似乎是一個不同的動物。
預期的新的擴展方法用法:
var results = entities.GroupBy("someFieldName").ToList();
擴展方法定義:
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
。所以我需要手動將列轉換爲對象,並且效果很好。
現在我正在用EF實體測試它,我猜EF試圖將轉換轉換爲等效的SQL,當然我知道這不存在。
錯誤:
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?
感謝您的任何指導。
Linq to Entities查詢提供程序需要知道要分組的屬性的類型;您需要爲方法調用添加一個泛型類型參數,您必須明確指定,並且可能會首先破壞使用屬性名稱的目的。 – Moho