Removing unnecessary boxing transform from C # expression

I'm currently trying to convert

Expression<Func<T,object>> 

before

 Expression<Func<T,bool>> 

The clock now shows me that my expression is holding on

 Expression<Func<T,object>> myExpression = model=>Convert(model.IsAnAirplane) 

I would like to simplify this for

 Expression<Func<T,bool>> myExpression = model=>model.IsAnAirplane 

Currently, I only manage to add the conversion, resulting in:

 Expression<Func<T,bool>> myExpression = model=>Convert(Convert(model.IsAnAirplane)) 

But since the base type is bool, I have to completely scratch the converters, right? I am familiar with visitor expressions, etc., but still cannot understand how to remove the converter.

Edit: this accepted answer to this question General unboxing of the expression Exect <Func <T, object →> to the expression <Func <T, TResult> (which may be a possible duplicate) does not work for me ... since the expression is passed to EF, you can see that it converts (Conversion ()) instead of just deleting the first one to convert ..., it leads to “Cannot apply the type“ System.Boolean ”to the type“ System.Object. ”LINQ to Entities only supports EDM listing- primitives or enumeration types. "

+6
source share
1 answer

You should remove any Convert wrappers using something like this:

 Expression<Func<YourModel, object>> boxed = m => m.IsAnAirplane; var unboxed = (Expression<Func<YourModel, bool>>)StripConvert(boxed); // ... public static LambdaExpression StripConvert<T>(Expression<Func<T, object>> source) { Expression result = source.Body; // use a loop in case there are nested Convert expressions for some crazy reason while (((result.NodeType == ExpressionType.Convert) || (result.NodeType == ExpressionType.ConvertChecked)) && (result.Type == typeof(object))) { result = ((UnaryExpression)result).Operand; } return Expression.Lambda(result, source.Parameters); } 

If you prefer, you can change the StripConvert to return Expression<Func<T,U>> instead of a simple LambdaExpression and perform the casting inside the method itself, but in this case you cannot take advantage of the type-output to call the method.

+4
source

All Articles