简体   繁体   English

Linq查询子查询

[英]Linq query with subquery

I have entity called UserPaymentHistory with Id, UserId, Price, PaymentDate. 我有一个名为UserPaymentHistory的实体,包含Id,UserId,Price,PaymentDate。 I need to get that row which will have a User with last PaymentDate. 我需要获得具有最后PaymentDate的User的那一行。

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 ? 有什么办法可以在一个查询中获得该记录吗? :) :)

Order payments by PaymentDate in descending order and select first one: PaymentDate按降序付款并选择第一个:

var userPayment = db.Repository<UserPayment>()
                      .Where(u => u.UserId == request.UserId)
                      .OrderByDescending(u => u.PaymentDate)
                      .FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM