Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,99 @@ GROUP BY (COALESCE("u"."FirstName", '') || ' ') || COALESCE("u"."LastName", '')
ORDER BY (COALESCE("u"."FirstName", '') || ' ') || COALESCE("u"."LastName", '')
```

#### How do I expand enum extension methods?
When you have an enum property and want to call an extension method on it (like getting a display name from a `[Display]` attribute), you can use the `ExpandEnumMethods` property on the `[Projectable]` attribute. This will expand the enum method call into a chain of ternary expressions for each enum value, allowing EF Core to translate it to SQL CASE expressions.

```csharp
public enum OrderStatus
{
[Display(Name = "Pending Review")]
Pending,

[Display(Name = "Approved")]
Approved,

[Display(Name = "Rejected")]
Rejected
}

public static class EnumExtensions
{
public static string GetDisplayName(this OrderStatus value)
{
// Your implementation here
return value.ToString();
}

public static bool IsApproved(this OrderStatus value)
{
return value == OrderStatus.Approved;
}

public static int GetSortOrder(this OrderStatus value)
{
return (int)value;
}

public static string Format(this OrderStatus value, string prefix)
{
return prefix + value.ToString();
}
}

public class Order
{
public int Id { get; set; }
public OrderStatus Status { get; set; }

[Projectable(ExpandEnumMethods = true)]
public string StatusName => Status.GetDisplayName();

[Projectable(ExpandEnumMethods = true)]
public bool IsStatusApproved => Status.IsApproved();

[Projectable(ExpandEnumMethods = true)]
public int StatusOrder => Status.GetSortOrder();

[Projectable(ExpandEnumMethods = true)]
public string FormattedStatus => Status.Format("Status: ");
}
```

This generates expression trees equivalent to:
```csharp
// For StatusName
@this.Status == OrderStatus.Pending ? GetDisplayName(OrderStatus.Pending)
: @this.Status == OrderStatus.Approved ? GetDisplayName(OrderStatus.Approved)
: @this.Status == OrderStatus.Rejected ? GetDisplayName(OrderStatus.Rejected)
: null

// For IsStatusApproved (boolean)
@this.Status == OrderStatus.Pending ? false
: @this.Status == OrderStatus.Approved ? true
: @this.Status == OrderStatus.Rejected ? false
: default(bool)
```

Which EF Core translates to SQL CASE expressions:
```sql
SELECT CASE
WHEN [o].[Status] = 0 THEN N'Pending Review'
WHEN [o].[Status] = 1 THEN N'Approved'
WHEN [o].[Status] = 2 THEN N'Rejected'
END AS [StatusName]
FROM [Orders] AS [o]
```

The `ExpandEnumMethods` feature supports:
- **String return types** - returns `null` as the default fallback
- **Boolean return types** - returns `default(bool)` (false) as the default fallback
- **Integer return types** - returns `default(int)` (0) as the default fallback
- **Other value types** - returns `default(T)` as the default fallback
- **Nullable enum types** - wraps the expansion in a null check
- **Methods with parameters** - parameters are passed through to each enum value call
- **Enum properties on navigation properties** - works with nested navigation

#### How does this relate to [Expressionify](https://github.com/ClaveConsulting/Expressionify)?
Expressionify is a project that was launched before this project. It has some overlapping features and uses similar approaches. When I first published this project, I was not aware of its existence, so shame on me. Currently, Expressionify targets a more focused scope of what this project is doing, and thereby it seems to be more limiting in its capabilities. Check them out though!

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFrameworkCore.Projectables
namespace EntityFrameworkCore.Projectables
{
/// <summary>
/// Declares this property or method to be Projectable.
Expand All @@ -23,5 +17,26 @@ public sealed class ProjectableAttribute : Attribute
/// or null to get it from the current member.
/// </summary>
public string? UseMemberBody { get; set; }

/// <summary>
/// Get or set whether to expand enum method/extension calls by evaluating them and generating ternary
/// expressions for each enum value.
/// </summary>
/// <remarks>
/// <para>
/// When enabled, method calls on enum values are rewritten into a chain of ternary expressions that call
/// the method for each possible enum value.
/// </para>
/// <para>
/// For example, <c>MyEnumValue.GetDescription()</c> would be expanded to:
/// <c>MyEnumValue == MyEnum.Value1 ? MyEnum.Value1.GetDescription() :
/// MyEnumValue == MyEnum.Value2 ? MyEnum.Value2.GetDescription() : null</c>
/// </para>
/// <para>
/// This is useful for <c>Where()</c> and <c>OrderBy()</c> clauses where the expression
/// needs to be translated to SQL.
/// </para>
/// </remarks>
public bool ExpandEnumMethods { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFrameworkCore.Projectables.Generator
{
Expand All @@ -16,14 +11,16 @@ public class ExpressionSyntaxRewriter : CSharpSyntaxRewriter
readonly INamedTypeSymbol _targetTypeSymbol;
readonly SemanticModel _semanticModel;
readonly NullConditionalRewriteSupport _nullConditionalRewriteSupport;
readonly bool _expandEnumMethods;
readonly SourceProductionContext _context;
readonly Stack<ExpressionSyntax> _conditionalAccessExpressionsStack = new();
readonly string? _extensionParameterName;
public ExpressionSyntaxRewriter(INamedTypeSymbol targetTypeSymbol, NullConditionalRewriteSupport nullConditionalRewriteSupport, SemanticModel semanticModel, SourceProductionContext context, string? extensionParameterName = null)

public ExpressionSyntaxRewriter(INamedTypeSymbol targetTypeSymbol, NullConditionalRewriteSupport nullConditionalRewriteSupport, bool expandEnumMethods, SemanticModel semanticModel, SourceProductionContext context, string? extensionParameterName = null)
{
_targetTypeSymbol = targetTypeSymbol;
_nullConditionalRewriteSupport = nullConditionalRewriteSupport;
_expandEnumMethods = expandEnumMethods;
_semanticModel = semanticModel;
_context = context;
_extensionParameterName = extensionParameterName;
Expand Down Expand Up @@ -55,30 +52,191 @@ public ExpressionSyntaxRewriter(INamedTypeSymbol targetTypeSymbol, NullCondition
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
// Fully qualify extension method calls
if (node.Expression is MemberAccessExpressionSyntax memberAccessExpressionSyntax)
if (node.Expression is not MemberAccessExpressionSyntax memberAccessExpressionSyntax)
{
var symbol = _semanticModel.GetSymbolInfo(node).Symbol;
if (symbol is IMethodSymbol { IsExtensionMethod: true } methodSymbol)
{
return SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ParseName(methodSymbol.ContainingType.ToDisplayString(NullableFlowState.None, SymbolDisplayFormat.FullyQualifiedFormat)),
memberAccessExpressionSyntax.Name
),
node.ArgumentList.WithArguments(
((ArgumentListSyntax)VisitArgumentList(node.ArgumentList)!).Arguments.Insert(0, SyntaxFactory.Argument(
(ExpressionSyntax)Visit(memberAccessExpressionSyntax.Expression)
)
return base.VisitInvocationExpression(node);
}

var symbol = _semanticModel.GetSymbolInfo(node).Symbol;
if (symbol is not IMethodSymbol methodSymbol)
{
return base.VisitInvocationExpression(node);
}

// Check if we should expand enum methods
if (_expandEnumMethods && TryExpandEnumMethodCall(node, memberAccessExpressionSyntax, methodSymbol, out var expandedExpression))
{
return expandedExpression;
}

// Fully qualify extension method calls
if (methodSymbol.IsExtensionMethod)
{
return SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ParseName(methodSymbol.ContainingType.ToDisplayString(NullableFlowState.None, SymbolDisplayFormat.FullyQualifiedFormat)),
memberAccessExpressionSyntax.Name
),
node.ArgumentList.WithArguments(
((ArgumentListSyntax)VisitArgumentList(node.ArgumentList)!).Arguments.Insert(0, SyntaxFactory.Argument(
(ExpressionSyntax)Visit(memberAccessExpressionSyntax.Expression)
)
)
);
}
)
);
}

return base.VisitInvocationExpression(node);
}

private bool TryExpandEnumMethodCall(InvocationExpressionSyntax node, MemberAccessExpressionSyntax memberAccess, IMethodSymbol methodSymbol, out ExpressionSyntax? expandedExpression)
{
expandedExpression = null;

// Get the receiver expression (the enum instance or variable)
var receiverExpression = memberAccess.Expression;
var receiverTypeInfo = _semanticModel.GetTypeInfo(receiverExpression);
var receiverType = receiverTypeInfo.Type;

// Handle nullable enum types
ITypeSymbol enumType;
var isNullable = false;
if (receiverType is INamedTypeSymbol { IsGenericType: true, Name: "Nullable" } nullableType &&
nullableType.TypeArguments.Length == 1 &&
nullableType.TypeArguments[0].TypeKind == TypeKind.Enum)
{
enumType = nullableType.TypeArguments[0];
isNullable = true;
}
else if (receiverType?.TypeKind == TypeKind.Enum)
{
enumType = receiverType;
}
else
{
// Not an enum type
return false;
}

// Get all enum members
var enumMembers = enumType.GetMembers()
.OfType<IFieldSymbol>()
.Where(f => f.HasConstantValue)
.ToList();

if (enumMembers.Count == 0)
{
return false;
}

// Visit the receiver expression to transform it (e.g., @this.MyProperty)
var visitedReceiver = (ExpressionSyntax)Visit(receiverExpression);

// Get the original method (in case of reduced extension method)
var originalMethod = methodSymbol.ReducedFrom ?? methodSymbol;

// Get the return type of the method to determine the default value
var returnType = methodSymbol.ReturnType;

// Build a chain of ternary expressions for each enum value
// Start with default(T) as the fallback for non-nullable types, or null for nullable/reference types
ExpressionSyntax defaultExpression;
if (returnType.IsReferenceType || returnType.NullableAnnotation == NullableAnnotation.Annotated ||
returnType is INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T })
{
defaultExpression = SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression);
}
else
{
// Use default(T) for value types
defaultExpression = SyntaxFactory.DefaultExpression(
SyntaxFactory.ParseTypeName(returnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)));
}

var currentExpression = defaultExpression;

// Create the enum value access: EnumType.Value
var enumAccessValues = enumMembers
.AsEnumerable()
.Reverse()
.Select(m =>
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ParseTypeName(enumType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)),
SyntaxFactory.IdentifierName(m.Name)
)
);

// Build the ternary chain, calling the method on each enum value
foreach (var enumValueAccess in enumAccessValues)
{
// Create the method call on the enum value: ExtensionClass.Method(EnumType.Value)
var methodCall = CreateMethodCallOnEnumValue(originalMethod, enumValueAccess, node.ArgumentList);

// Create condition: receiver == EnumType.Value
var condition = SyntaxFactory.BinaryExpression(
SyntaxKind.EqualsExpression,
visitedReceiver,
enumValueAccess
);

// Create conditional expression: condition ? methodCall : previousExpression
currentExpression = SyntaxFactory.ConditionalExpression(
condition,
methodCall,
currentExpression
);
}

// If nullable, wrap in null check
if (isNullable)
{
var nullCheck = SyntaxFactory.BinaryExpression(
SyntaxKind.EqualsExpression,
visitedReceiver,
SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)
);

currentExpression = SyntaxFactory.ConditionalExpression(
nullCheck,
defaultExpression,
currentExpression
);
}

expandedExpression = SyntaxFactory.ParenthesizedExpression(currentExpression);
return true;
}

private ExpressionSyntax CreateMethodCallOnEnumValue(IMethodSymbol methodSymbol, ExpressionSyntax enumValueExpression, ArgumentListSyntax originalArguments)
{
// Get the fully qualified containing type name
var containingTypeName = methodSymbol.ContainingType.ToDisplayString(NullableFlowState.None, SymbolDisplayFormat.FullyQualifiedFormat);

// Create the method access expression: ContainingType.MethodName
var methodAccess = SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ParseName(containingTypeName),
SyntaxFactory.IdentifierName(methodSymbol.Name)
);

// Build arguments: the enum value as the first argument (for extension methods), followed by any additional arguments
var arguments = SyntaxFactory.SeparatedList<ArgumentSyntax>();
arguments = arguments.Add(SyntaxFactory.Argument(enumValueExpression));

// Add any additional arguments from the original call
foreach (var arg in originalArguments.Arguments)
{
arguments = arguments.Add((ArgumentSyntax)Visit(arg));
}

return SyntaxFactory.InvocationExpression(
methodAccess,
SyntaxFactory.ArgumentList(arguments)
);
}

public override SyntaxNode? VisitInterpolation(InterpolationSyntax node)
{
// Visit the expression first
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ static IEnumerable<string> GetNestedInClassPathForExtensionMember(ITypeSymbol ex
.OfType<string?>()
.FirstOrDefault();

var expandEnumMethods = projectableAttributeClass.NamedArguments
.Where(x => x.Key == "ExpandEnumMethods")
.Select(x => x.Value.Value is bool b && b)
.FirstOrDefault();

var memberBody = member;

if (useMemberBody is not null)
Expand Down Expand Up @@ -152,6 +157,7 @@ x is IPropertySymbol xProperty &&
var expressionSyntaxRewriter = new ExpressionSyntaxRewriter(
targetTypeForRewriting,
nullConditionalRewriteSupport,
expandEnumMethods,
semanticModel,
context,
extensionParameter?.Name);
Expand Down
Loading