Get Display Enum in LINQ

c# entity-framework entity-framework-6 linq

Popular Answer

You must enumerate first, then use reflection to get the property since LINQ is unaware of that extension function.

public static class EnumExtensions
{
    public static string GetDisplayName(this Enum value)
    {
        var attribute = (DisplayNameAttribute) value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(false)
            .Where(a => a is DisplayNameAttribute)
            .FirstOrDefault();

        return attribute != null ? attribute.DisplayName : value.ToString();
    }
}

You can test this out and let us know whether it works even if I can't test it right now:

var query = dbo.Records.Include(x => x.Prescriptions).OrderByDescending(x => x.Id).AsEnumerable()
            .Select(x => new
            {
                Id = x.Id,
                Care = new
                {
                    x.StartDate,
                    x.ForwardedBy,
                },
                Prescriptions = x.Prescriptions.Select(p => new
                {
                    p.Medicament,
                    p.IntervalUse.GetDisplayName()
                }),
            });
1
7/27/2016 10:51:36 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow