有没有一种方法可以在linq查询的select部分进行循环?

时间:2019-09-16 13:04:58

标签: c# linq

我正在为用户退回CommissionDocuments。 CommissionDocument包含许多用户可以获取佣金的政策。

所以我想对CommissionDocument中每个策略的佣金进行总结。

我尝试使用无效的Sum()方法。

查询

    public async Task<List<Commission>> FetchAsync(Agent agent)
    {
      return await _agentsContext.ScanCommDoc
        .Include(x => x.CommissionStatement)
        .Where(x => x.AgentId == agent.AgentId && x.Type == FileType.CommissionStatement
           && x.CommissionStatement.PaymentYear == x.ScanDate.AddMonths(-1).Year
           && x.CommissionStatement.PaymentMonth == x.ScanDate.AddMonths(-1).Month)
           .Select(x => new AgentCommission { ScanDate = x.ScanDate, FileUrl = x.FileUrl Commission = (x.AgentCommission .Amount + x.AgentCommission .Vat) })
           .GroupBy(x => x.ScanDate).Select(x => x.FirstOrDefault()).Take(2)
           .OrderByDescending(x => x.ScanDate).ToListAsync();

代理人佣金(数据库表)

public class AgentCommissionStatement
  {
    public int BrokerId { get; set; }

    public Byte PaymentMonth { get; set; }

    public Int16 PaymentYear { get; set; }

    public decimal Amount { get; set; }

    public decimal Vat { get; set; }
  }

委员会映射类

  public class AgentCommission
  {
    public int AgentId { get; set; }
    public string FileUrl { get; set; }
    public Guid? FileGuid { get; set; }
    public DateTime ScanDate { get; set; }
    public Decimal? Commission { get; set; }
  }
 public class ScanCommDoc
  {

    public int Id { get; set; }

    public int AgentId { get; set; }

    public string FileUrl { get; set; }

    public Guid? FileGuid { get; set; }

    public PolicyDetail Policy { get; set; }

    public FileType Type { get; set; }

    public DateTime ScanDate { get; set; }

    public CommissionStatement CommissionStatement { get; set; }
  }

1 个答案:

答案 0 :(得分:0)

感谢您的所有帮助和建议。 以下是我正在尝试做的事情。 我能够得到佣金的总和。

public async Task<List<Commission>> FetchAsync(Agent agent)
    {
        return await _agentsContext.ScanCommDoc
          .Include(x => x.CommissionStatement)
          .Where(x => x.AgentId == agent.AgentId && x.Type == FileType.CommissionStatement
             && x.CommissionStatement.PaymentYear == x.ScanDate.AddMonths(-1).Year
             && x.CommissionStatement.PaymentMonth == x.ScanDate.AddMonths(-1).Month)
             .Select(x => new { x.ScanDate, x.FileUrl, x.FileGuid,  commission = (x.CommissionStatement.Amount + x.CommissionStatement.Vat) })
             .GroupBy(x => new { x.FileGuid, x.FileUrl, x.ScanDate })
                     .Select(p => new AgentCommission
                     {
                         FileGuid = p.Key.FileGuid,
                         FileUrl = p.Key.FileUrl,
                         ScanDate = p.Key.ScanDate,
                         Commission = p.Sum(x => x.commission)
                     })
             .OrderByDescending(x => x.ScanDate).Take(10).ToListAsync();
    }