I have query like below:
var query = from operation in dbContext.Operations
select new OperationsDto
{
Id = o.Id,
ProcessDate = o.ProcessDate,
Amount = o.Credit
//Balance = ...
};
There is no Balance property in Operation entity. I have to calculate it. Balance => (sum of operations' Amount which operation has happened before current operation ProcessDate) + current Amount). For example:
Id ProcessDate Amount Balance
1 2021.02.01 +100$ 50 + 100 = +150$ (
2 2021.02.03 -200$ 150$ + (-200) = -50$ (this get sum of amount where record's process date before 2021.02.03)
3 2019.01.01 +50$ 0 + 50$ = 50$ (because this is first operation. there is not record before 2019.01.01)
I want this in EF Core. I know I can do this using foreach after retrieve data like below:
var operations = query.ToList();
foreach (var operation in operations)
{
operation.Balance = operations.Where(x => x.ProcessDate < operation.ProcessDate).Sum(o => o.Debit - o.Credit);
}
But I need to calculate in query