I have a performance problem in projections of Entity Framework.
My find has a projection with a list of sub-property:
public List<UserProjection> FindUserAndLastOrder(List<Guid> idsUser)
{
return _entity.Where(x => idsUser.Contains(x.Id)).Select(x => new UserProjection()
{
Email = x.Email,
LastOrderId = x.Orders.OrderByDescending(order => order.CreatedAt).First().Id,
Price = x.Orders.OrderByDescending(order=> order.CreatedAt).First().Price
}).ToList();
}
Then run the query and it executes two subqueries: one for getting order id and the other for getting price
Has a solution for saving subquery in variable and reusing value in two points?
entities examples:
public class User : BaseEntity
{
public string Email { get; }
public string Password { get; private set; }
public byte[] Key { get; private set; }
public List<Order> Orders { get; set;}
}
public class Order : BaseEntity
{
public double Price { get; set; }
public Guid IdUser { get; set; }
}
public class UserProjection
{
public string Email { get; set; }
public Guid LastOrderId { get; set; }
public double Price { get; set; }
}