You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:15:07