Skip to content

Expand enum types properties' extension methods to the generated expression tree #149

@PhenX

Description

@PhenX

While it is not useful in .Select() projections because it is resolved on runtime by EF core, it is useful when used in .Where() and .OrderBy()

Given this example :

public static class EnumExtensions
{
    public static T? GetAttribute<T>(this Enum value) where T : Attribute
    {
        var type = value.GetType();
        var memberInfo = type.GetMember(value.ToString()).FirstOrDefault();
        return memberInfo?.GetCustomAttribute<T>();
    }
}

namespace Foo {
    public static class EntityExtensions
    {
        public enum CustomEnum
        {
            [Display(Name = "Value 1")]
            Value1,
            
            [Display(Name = "Value 2")]
            Value2,
        }
        
        public record Entity
        {
            public int Id { get; set; }
            public CustomEnum? MyValue { get; set; }
            
            [Projectable(EnumPropertiesExapend = true)] // New ProjectableAttribute parameter here
            public string? MyEnumName => MyValue?.GetAttribute<DisplayAttribute>()?.Name;
        }
    }
}

MyEnumName would be expanded to an sequence of ternary expressions (because switch are not suppored in expression trees), like this :

public string MyEnumName => MyValue == CustomEnum.Value1 ? "Value 1" : MyValue == CustomEnum.Value2 ? "Value 2" : null;

Here, GetAttribute() is just an example, it could be any user specified extension, the value would be resolved during compilation to the expression tree source generation.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions