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