I have a scenario where I have to order by from a table using EF8, which contains string as a value, but I have to convert it to int with some constant and then order by with the int value.
var orderedQueryable = _dbContext.tableName
.Where(q => (!q.IsDismissed) && (statuses.Any(s => q.Status == s)))
.OrderBy(q => StatusOrders[q.Status])
.ThenByDescending(q => q.LastUpdatedAt)
.GroupBy(q => q.id)
.Select(g => g.OrderByDescending(q => q.LastUpdatedAt).First());
Dictionary<string, int> StatusOrders = new Dictionary<string, int> {
{"Executing", 1},
{"Submitted", 2},
{"Error", 3},
{"Completed", 4},
};
I know the reason because EF cannot create Query to fetch data with the linq, It works fine if the query is executed. I believe it can be achieved by Linq.Expressions.Expression, but its confusing. Can someone help me with this.
I wrote it like below, I am sure this is not correct approach
var orderedQueryable = _dbContext.tableName
.Where(q => (!q.IsDismissed) && (statuses.Any(s => q.Status == s)))
.OrderBy(q => (q.Status == StatusOrders .Executing? 1: q.Status == StatusOrders .Submitted? 2 : q.Status == StatusOrders .Error ? 3 : q.Status == StatusOrders .Completed ? 4 : 0))
.ThenByDescending(q => q.LastUpdatedAt)
.GroupBy(q => q.id)
.Select(g => g.OrderByDescending(q => q.LastUpdatedAt).First());