Entity Framework 从列中得到 运行 总数

Entity Framework getting a running total from columns

以前可能有人问过这个问题,但我正在努力寻找答案。我有以下代码,试图获得 运行 总数。

这不是我以前见过的错误,我对它的实际含义或如何修复它感到困惑,并尽可能将其保留在一个查询中。但是,将对更好的方法持开放态度。

我在错误发生的地方添加了注释,里面的错误是什么Visual Studio。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

    class VMAccountWindow : BaseViewModel
    {

        public VMAccount()
        {
            using (DBContext db = new DBContext())
            {
                decimal currentTotal = 0;

                var tl = db.Transaction
                    .OrderByDescending(
                        p => p.TransactionDate
                    )
                    .Select(p => new TransactionList
                    {
                        AccountId = p.AccountId,
                        TransactionDate = p.TransactionDate,
                        Deposit = p.TransCode == "Deposit" ? p.TransactionAmount.ToString() : "",
                        Withdrawal = p.TransCode == "Deposit" ? "" : p.TransactionAmount.ToString(),
                        Notes = p.Notes,
                        // Following gives an error about Expression tree may not contain an assignment operator
                        AccountBalance = currentTotal += p.TransCode == "Deposit" ? p.TransactionAmount : -p.TransactionAmount
                    })
                .Where(o => o.AccountId == 1)
                .ToList();
            }
        }
    }

    public class TransactionList
    {
        public int AccountId { get; set; }
        public string TransactionDate { get; set; }
        public string Deposit { get; set; }
        public string Withdrawal { get; set; }
        public string Notes { get; set; }
        public decimal AccountBalance { get; set; }
    }

如有任何帮助,我们将不胜感激。

您在初始分配 currentTotal

后使用 +=

将其更改为 +,如下所示:

AccountBalance = currentTotal + p.TransCode == "Deposit" ? p.TransactionAmount : -p.TransactionAmount                    

解决办法是先把结果变成一个列表,然后再做第二个select,我没有看到这个,因为我所做的搜索只显示获取数据。没有说明如何。

由于这可能会绊倒其他新开发人员,我在下面粘贴了工作示例,这是所有试图提供帮助的人的建议的结果。

var tl = db.Transaction
    .Where(o => o.AccountId == 1)
    .OrderBy(p => p.TransactionDate)
    .ToList()
    .Select(i =>
            {
                currentTotal += p.TransCode == "Deposit" ? p.TransactionAmount : 0;
                return new TransactionList
                {
                    ToAccountId = i.ToAccountId,
                    TransactionDate = i.TransactionDate,
                    AccountBalance = currentTotal
                };
            }
    )
    .ToList();

不幸的是,我不知道为什么必须先把它变成一个列表,然后再做 select,所以如果有人能插话原因,如果有人谁知道可以解释那部分。