I have this expression:
public static readonly Expression<Func<ApplicationUser, decimal>> EfficiencyPercentExpr = e =>
(e.ExecutorOrders.Where(x => x.Added >= DbFunctions.AddDays(SqlFunctions.GetUtcDate(), -30)).Count(x => x.Status != Order.OrderStatus.Deleted) > 0)
?
(
e.ExecutorOrders.Where(x => x.Added >= DbFunctions.AddDays(SqlFunctions.GetUtcDate(), -30)).Count(x => x.Status != Order.OrderStatus.Deleted)
/
e.ExecutorOrders.Where(x => x.Added >= DbFunctions.AddDays(SqlFunctions.GetUtcDate(), -30)).Count()
)
:
0
;
This expression calculates the user's efficiency by calculating the percentage of successful orders from a total of the last 30 days.
How can I make it more clear?
Update:
There is a second approach of writing the expression, but it generates more expensive SQL query.
private static readonly Expression<Func<ApplicationUser, decimal>> efficiencyPercentExpr = e =>
e.ExecutorOrders.Where(x => !x.IsNotConsidered && x.Added >= DbFunctions.AddDays(SqlFunctions.GetUtcDate(), -30))
.GroupBy(x => 1, (k, g) => new { Count = g.Count(), CountUndeleted = g.Count(x => x.Status != Order.OrderStatus.Deleted) })
.Select(x => x.CountUndeleted > 0 ? (decimal)x.CountUndeleted / (decimal)x.Count : 0).FirstOrDefault();