This is a follow up to my question Dynamic Expression Generation Issues with ValueTypes adding in a new variable: Entity Framework. Now that I am able to generate the necessary Expressions when dealing with ValueTypes, I'm running into a new issue when Linq-to-Entities attempts to process the query. I receive the following error:
System.NotSupportedException: Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
So apparently Linq-to-Entities is not a fan of boxed values. This works when I force the query to process (via ToList()
or another type method), but not when it's done by the database, which would be ideal.
Is there a way to make this method more generic to make Linq-to-Entities happy? Keep in mind that I don't know the type of the property until runtime.
public IEnumerable<Expression<Func<T, object>>> GetExpressions<T>(string sortedColumn) where T : IReportRecord
{
var columns = GetFullSortOrder(sortedColumn);
var typeParameter = Expression.Parameter(typeof(T));
foreach (var c in columns)
{
var propParameter = Expression.Property(typeParameter, c);
if (propParameter.Type.IsValueType)
{
var boxedPropParameter = Expression.Convert(propParameter, typeof(object));
yield return Expression.Lambda<Func<T, object>>(boxedPropParameter, typeParameter);
}
else
{
yield return Expression.Lambda<Func<T, object>>(propParameter, typeParameter);
}
}
}