如何使用LINQ获取ASP.NET API项目中客户的最新支付金额
实现逻辑
要查询指定客户的最后一笔有效支付,按以下规则处理即可:
- 筛选对应
CustomerId的所有支付记录 - 过滤掉
FeePaid为0的无效支付记录 - 因为
PayId是自增字段,值越大代表支付生成时间越晚,直接按PayId倒序排序 - 取排序后的第一条记录的
FeePaid值,就是你要的最后一笔有效支付金额
代码示例
首先假设你的支付表对应实体类和DbContext定义如下:
// 支付记录实体类 public class Payment { public string CustomerId { get; set; } public int PayId { get; set; } public decimal FeePaid { get; set; } } // 数据库上下文 public class AppDbContext : DbContext { public DbSet<Payment> Payments { get; set; } // 其余配置省略 }
ASP.NET API推荐用异步查询写法,性能更好:
// 假设你已经在控制器/服务中注入了AppDbContext,targetCustomerId为你要查询的客户ID decimal? lastValidFee = await _dbContext.Payments .Where(p => p.CustomerId == targetCustomerId && p.FeePaid > 0) .OrderByDescending(p => p.PayId) .Select(p => p.FeePaid) .FirstOrDefaultAsync();
如果需要处理无有效支付的边界场景,可以调整为以下写法:
var lastValidPayment = await _dbContext.Payments .Where(p => p.CustomerId == targetCustomerId && p.FeePaid > 0) .OrderByDescending(p => p.PayId) .FirstOrDefaultAsync(); if (lastValidPayment == null) { // 自定义无有效支付时的处理逻辑,比如返回0、抛业务异常等 } else { decimal validAmount = lastValidPayment.FeePaid; // 你示例中的结果为30.00 }
上述查询会被EF Core自动翻译为SQL,过滤、排序、取数逻辑都在数据库端执行,不会加载全量数据,性能有保障。
内容的提问来源于stack exchange,提问作者canbrian
相关产品推荐
相关产品推荐

