EF Core 5 with Sum

岁酱吖の 提交于 2020-12-12 05:39:57

问题


Repost model class:

public class TransactionDayReport
{
    public Decimal TotalAmount { get; set; }
    public ICollection<TransactionResponse> TransactionResponses { get; set; } = null!;
}

This is my repository method

public async Task<IEnumerable<Transaction>> SearchTransactionAsync(SearchTransaction search)
{
    var query = _context.Transactions
                        .Include(t => t.Branch)
                        .Include(t => t.Customer)
                        .AsQueryable();    

    if (search.CIN != null)               
        query = query.Where(t => t.Customer.CIN.Contains(search.CIN));

    if (search.ValueDate != null)
        query = query.Where(t => t.ValueDate.Date == search.ValueDate.Date);

    return await query.ToListAsync();
}

Service method:

public async Task<TransactionResponse> SearchTransactions(SearchTransaction search)
{
    var transactionList = await _unitOfWork.Transactions.SearchTransactionAsync(search);
    var mapped = ObjectMapper.Mapper.Map<TransactionDayReport>(transactionList);
    return mapped;
}

I need to send total amount in service class..

am looking similar to this

But I am confused how to get addition sum added to my dto. Please can anyone suggest a solution? Thanks


回答1:


The only way to also calculate the sum on the DB is to run another query on the DB, unless the DB query can be re-written to return both the sum and the data.

If you're ok with calculating the Sum on the client, it's more straightforward. Here are some options I could think of:

  1. You could configure the mapper to set the sum.
  2. You could set the sum after performing the mapping in SearchTransactions().
  3. You could change the DTO to calculate the Sum (in which case it wouldn't be a POCO anymore, but I think this is a reasonable approach too):
    public class TransactionDayReport
    {
        private decimal? _totalAmount = null;
        public decimal TotalAmount { get {
            if(_totalAmount is not null) return _totalAmount; // new C# 9 feature :)
            _totalAmount = // calculate total amount here
            return _totalAmount;
        }
        public ICollection<TransactionResponse> TransactionResponses { get; set; } = null!;
    }
    


来源:https://stackoverflow.com/questions/65179783/ef-core-5-with-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!