Get Display Enum in LINQ

c# entity-framework entity-framework-6 linq

Question

How get a display/description enum in LINQ query?

For example

 var query = dbo.Records.AsQueryable()
              .Select(x => new
              {
                  Id = x.Id,
                  Care = new
                  {
                      x.StartDate,
                      x.ForwardedBy,
                  },
                  Prescriptions = x.Prescriptions.Select(p => new
                  {
                      p.Medicament,
                      p.IntervalUse //My Enum, how get Display name?
                  }),
              }).OrderByDescending(x => x.Id);

This query is an exampleand I need to be AsQueryable to generate faster query in my database

1
0
7/27/2016 9:33:09 PM

Popular Answer

Since LINQ doesn't know about that extension method, you will have to enumerate first, then get the attribute using reflection.

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();
    }
}

I can't test this right now, but you may try this and let us know if it works:

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