我有一个名为 UserPaymentHistory 的实体,其中包含 Id、UserId、Price、PaymentDate。 我需要获取具有最后一个付款日期的用户的那一行。
我可以这样查询:
var lastPaymentDate =
db.Repository<UserPayment>()
.Where(u => u.UserId == 1)
.Select(x => x.PaymentDate)
.Max();
然后:
var userPayment = db.Repository<UserPayment>()
.Where(u => u.UserId == request.UserId
&& u.PaymentDate == lastPaymentDate).Single();
有什么方法可以在一次查询中获取该记录? :)
最佳答案
按 PaymentDate 降序排列付款并选择第一个:
var userPayment = db.Repository<UserPayment>()
.Where(u => u.UserId == request.UserId)
.OrderByDescending(u => u.PaymentDate)
.FirstOrDefault();
关于c# - 带有子查询的 Linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19013845/