The code you've shown creates expression trees that build conditional logic for mapping enum values to descriptions. However, the way you're using it with .Compile().Invoke() won't translate to SQL - it will force client-side evaluation.
To make this translatable to SQL, you need to use the expression directly in your LINQ query without compiling it. Here's how:
You're absolutely right - Expression doesn't have an Invoke method. I apologize for the confusion in my previous response. Let me provide a corrected solution.
The issue is that you need to compose expressions properly to make them translatable to SQL. Here are a few approaches:
Approach 1: Direct Expression Composition
public static class ExpressionExtensions
{
public static Expression<Func<TSource, TResult>> Compose<TSource, TIntermediate, TResult>(
this Expression<Func<TSource, TIntermediate>> first,
Expression<Func<TIntermediate, TResult>> second)
{
var param = first.Parameters[0];
var body = second.Body.Replace(second.Parameters[0], first.Body);
return Expression.Lambda<Func<TSource, TResult>>(body, param);
}
private static Expression Replace(this Expression expression, Expression searchEx, Expression replaceEx)
{
return new ReplaceExpressionVisitor(searchEx, replaceEx).Visit(expression);
}
private class ReplaceExpressionVisitor : ExpressionVisitor
{
private readonly Expression _searchEx;
private readonly Expression _replaceEx;
public ReplaceExpressionVisitor(Expression searchEx, Expression replaceEx)
{
_searchEx = searchEx;
_replaceEx = replaceEx;
}
public override Expression Visit(Expression node)
{
return node == _searchEx ? _replaceEx : base.Visit(node);
}
}
}
A simpler approach is to build the expression directly in your Select statement:
public static class EventDescriptionExpressionProvider
{
public static Expression<Func<TEntity, string>> BuildDescriptionExpression<TEntity, TEnum>(
Expression<Func<TEntity, TEnum>> propertySelector)
where TEnum : Ardalis.SmartEnum.SmartEnum<TEnum, int>, IDescriptionLocalizable
{
var param = propertySelector.Parameters[0];
var propertyAccess = propertySelector.Body;
var valueProperty = typeof(TEnum).GetProperty("Value");
var valueAccess = Expression.Property(propertyAccess, valueProperty);
Expression body = Expression.Constant(null, typeof(string));
foreach (var enumInstance in Ardalis.SmartEnum.SmartEnum<TEnum>.List.OrderByDescending(x => x.Value))
{
body = Expression.Condition(
Expression.Equal(valueAccess, Expression.Constant(enumInstance.Value)),
Expression.Constant(enumInstance.Description()),
body
);
}
return Expression.Lambda<Func<TEntity, string>>(body, param);
}
}
User
Expression of type 'System.Nullable`1[System.Int32]' cannot be used for parameter of type 'System.Int32' (Parameter 'arg0')
at System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, String methodParamName, String argumentParamName, Int32 index)
at System.Linq.Expressions.Expression.Invoke(Expression expression, Expression arg0)
Assistant
The error indicates that you're trying to pass a nullable int (int?) to a parameter that expects a non-nullable int. This is likely happening because your SystemEventType property might be nullable, but the expression expects a non-nullable value.
Here's how to fix this issue:
Solution 1: Handle Nullable Types in the Expression Builder
Modify your BuildDescriptionLambda method to handle nullable types:
private static Expression<Func<TEnum?, TRet>> BuildDescriptionLambda<TEnum, TRet>(
Func<TEnum, TRet> fieldSelector)
where TEnum : Ardalis.SmartEnum.SmartEnum<TEnum, int>, IDescriptionLocalizable
{
ParameterExpression valueParam = Expression.Parameter(typeof(TEnum?), "value");
// Check for null first
var nullCheck = Expression.Equal(valueParam, Expression.Constant(null, typeof(TEnum?)));
// Access the Value property through the nullable type
var hasValueProperty = typeof(TEnum?).GetProperty("HasValue");
var valueProperty = typeof(TEnum?).GetProperty("Value");
var nonNullableValue = Expression.Property(valueParam, valueProperty);
var intValueProperty = typeof(TEnum).GetProperty("Value");
var intValueAccess = Expression.Property(nonNullableValue, intValueProperty);
IOrderedEnumerable<TEnum> orderedEnum = Ardalis.SmartEnum.SmartEnum<TEnum>.List.OrderByDescending(x => x.Value);
Expression body = Expression.Constant(default(TRet), typeof(TRet));
foreach (TEnum enumInstance in orderedEnum)
{
body = Expression.Condition(
Expression.Equal(intValueAccess, Expression.Constant(enumInstance.Value)),
Expression.Constant(fieldSelector(enumInstance)),
body
);
}
// Wrap the entire body in a null check
body = Expression.Condition(
nullCheck,
Expression.Constant(default(TRet), typeof(TRet)),
body
);
return Expression.Lambda<Func<TEnum?, TRet>>(body, valueParam);
}
Solution 2: Create Separate Expressions for Nullable and Non-Nullable
public static class EventDescriptionExpressionProvider
{
// For non-nullable
public static readonly Expression<Func<SystemEventTypeLookup, string>> GetSystemEventDescriptionExpression =
BuildDescriptionLambda<SystemEventTypeLookup, string>(set => set.Description());
// For nullable
public static readonly Expression<Func<SystemEventTypeLookup?, string>> GetSystemEventDescriptionExpressionNullable =
BuildNullableDescriptionLambda<SystemEventTypeLookup, string>(set => set.Description());
private static Expression<Func<TEnum?, TRet>> BuildNullableDescriptionLambda<TEnum, TRet>(
Func<TEnum, TRet> fieldSelector)
where TEnum : Ardalis.SmartEnum.SmartEnum<TEnum, int>, IDescriptionLocalizable
{
ParameterExpression valueParam = Expression.Parameter(typeof(TEnum?), "value");
var nullConstant = Expression.Constant(null, typeof(TEnum?));
var defaultReturn = Expression.Constant(default(TRet), typeof(TRet));
// Build the non-nullable expression
var nonNullableExpr = BuildDescriptionLambda<TEnum, TRet>(fieldSelector);
// Create a conditional that checks for null first
var body = Expression.Condition(
Expression.Equal(valueParam, nullConstant),
defaultReturn,
Expression.Invoke(nonNullableExpr, Expression.Property(valueParam, "Value"))
);
return Expression.Lambda<Func<TEnum?, TRet>>(body, valueParam);
}
}
This translates to SQL as a CASE WHEN statement:
SELECT
CASE
WHEN [r].[SystemEventTypeValue] = 5 THEN N'Description5'
WHEN [r].[SystemEventTypeValue] = 4 THEN N'Description4'
WHEN [r].[SystemEventTypeValue] = 3 THEN N'Description3'
WHEN [r].[SystemEventTypeValue] = 2 THEN N'Description2'
WHEN [r].[SystemEventTypeValue] = 1 THEN N'Description1'
ELSE NULL
END AS [EventValue]
FROM [Records] AS [r]
Alternative Approach
If you're having trouble with the expression composition, you could also create a method that builds the expression inline:
public static Expression<Func<TEntity, string>> GetDescriptionExpression<TEntity, TEnum>(
Expression<Func<TEntity, TEnum>> propertySelector)
where TEnum : Ardalis.SmartEnum.SmartEnum<TEnum, int>, IDescriptionLocalizable
{
var param = propertySelector.Parameters[0];
var propertyAccess = propertySelector.Body;
var valueProperty = typeof(TEnum).GetProperty("Value");
var valueAccess = Expression.Property(propertyAccess, valueProperty);
Expression body = Expression.Constant(null, typeof(string));
foreach (var enumInstance in Ardalis.SmartEnum.SmartEnum<TEnum>.List.OrderByDescending(x => x.Value))
{
body = Expression.Condition(
Expression.Equal(valueAccess, Expression.Constant(enumInstance.Value)),
Expression.Constant(enumInstance.Description()),
body
);
}
return Expression.Lambda<Func<TEntity, string>>(body, param);
}
// Usage:
var descriptionExpression = GetDescriptionExpression<Record, SystemEventTypeLookup>(r => r.SystemEventType);
var query = context.Records.Select(descriptionExpression);
This approach builds the entire expression tree in one go, making it easier for EF Core to translate to SQL.
Usage:
var descriptionExpression = EventDescriptionExpressionProvider
.BuildDescriptionExpression<Record, SystemEventTypeLookup>(r => r.SystemEventType);
var query = context.Records.Select(descriptionExpression);
Approach 3: Using LINQKit (NuGet Package)
If you want a more robust solution, you can use the LINQKit library:
The key point is that for EF Core to translate to SQL, you need to provide it with a complete expression tree that it can analyze. Using .Compile() breaks this because it converts the expression into a delegate, which EF Core cannot translate.
Solution 3: Generic Approach with Runtime Type Detection
public static Expression<Func<TEntity, string>> BuildDescriptionExpression<TEntity, TEnum>(
Expression<Func<TEntity, TEnum?>> propertySelector)
where TEnum : struct, Ardalis.SmartEnum.SmartEnum<TEnum, int>, IDescriptionLocalizable
{
var param = propertySelector.Parameters[0];
var propertyAccess = propertySelector.Body;
// Check if the property is null
var nullCheck = Expression.Equal(propertyAccess, Expression.Constant(null, typeof(TEnum?)));
// Access Value property of nullable
var hasValueAccess = Expression.Property(propertyAccess, "HasValue");
var valueAccess = Expression.Property(propertyAccess, "Value");
var intValueAccess = Expression.Property(valueAccess, "Value");
Expression body = Expression.Constant(null, typeof(string));
foreach (var enumInstance in Ardalis.SmartEnum.SmartEnum<TEnum>.List.OrderByDescending(x => x.Value))
{
body = Expression.Condition(
Expression.AndAlso(
hasValueAccess,
Expression.Equal(intValueAccess, Expression.Constant(enumInstance.Value))
),
Expression.Constant(enumInstance.Description()),
body
);
}
// Wrap in null check
body = Expression.Condition(
nullCheck,
Expression.Constant(null, typeof(string)),
body
);
return Expression.Lambda<Func<TEntity, string>>(body, param);
}
Solution 4: Using LINQKit with Null Handling
If you're using LINQKit:
public static Expression<Func<TEnum?, string>> GetNullableDescriptionExpression<TEnum>()
where TEnum : struct, Ardalis.SmartEnum.SmartEnum<TEnum, int>, IDescriptionLocalizable
{
return value => value.HasValue
? GetSystemEventDescriptionExpression.Invoke(value.Value)
: null;
}
Then use it like:
var query = context.Records
.AsExpandable()
.Select(r => new
{
EventValue = r.SystemEventType.HasValue
? EventDescriptionExpressionProvider.GetSystemEventDescriptionExpression.Invoke(r.SystemEventType.Value)
: null
});
The key is to handle the nullable type properly by checking for null before accessing the value, and ensuring that the expression tree correctly represents this logic for EF Core to translate to SQL.