Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query with subquery

Tags:

c#

linq

I have entity called UserPaymentHistory with Id, UserId, Price, PaymentDate. I need to get that row which will have a User with last PaymentDate.

I can do query like this:

var lastPaymentDate =
    db.Repository<UserPayment>()
            .Where(u => u.UserId == 1)
            .Select(x => x.PaymentDate)
            .Max();

And then:

var userPayment = db.Repository<UserPayment>()
                      .Where(u => u.UserId == request.UserId 
                      && u.PaymentDate == lastPaymentDate).Single();

Is any way that I could get that record in one query ? :)

like image 989
mardok Avatar asked Feb 27 '26 13:02

mardok


1 Answers

Order payments by PaymentDate in descending order and select first one:

var userPayment = db.Repository<UserPayment>()
                      .Where(u => u.UserId == request.UserId)
                      .OrderByDescending(u => u.PaymentDate)
                      .FirstOrDefault();
like image 135
Sergey Berezovskiy Avatar answered Mar 01 '26 03:03

Sergey Berezovskiy