我有两张桌子
Incomes:
[Id]
[AmountOfMoneyEarnt]
[Date]
[AccountId]
和
Spendings
[Id]
[AmountOfMoneySpent]
[Date]
[AccountId]
我想在C#中创建一个LINQ查询来获得总收入的总和和总支出的总和,但我想在一次往返中查询。显然,我想知道帐户余额,TotalIncome-TotalSpendings与一个SQL服务器往返。这有可能吗?
谢谢!
答案 0 :(得分:2)
为了在一次往返中执行此操作,您可以使用LINQ Concat运算符,该运算符与常见匿名类型投影上的SQL UNION ALL
等效,包括帐户ID和金额(收入为正数)并且支出为负数),按帐户对结果进行分组,并像这样计算余额
var query =
db.Incomes.Select(i => new { AccountId = i.AccountId, Amount = i.AmountOfMoneyEarnt })
.Concat(
db.Spendings.Select(s => new { AccountId = s.AccountId, Amount = -s.AmountOfMoneySpent })
)
.GroupBy(e => e.AccountId)
.Select(g => new { AccountId = g.Key, Balance = g.Sum(e => e.Amount) });
如果您只需要特定帐户的余额,那么它可能就像这样
var accountId = ...;
var accountBalance =
db.Incomes.Where(i => i.AccountId == accountId).Select(i => i.AmountOfMoneyEarnt)
.Concat(
db.Spendings.Where(s => s.AccountId == accountId).Select(s => -s.AmountOfMoneySpent)
)
.DefaultIfEmpty()
.Sum();
答案 1 :(得分:1)
如果表格根本没有关联,并且您想选择一个sclar值:
var totalIncomesAndSpendings = new {
TotalIncomes = db.Incomes.Sum(x => x.AmountOfMoneyEarnt),
TotalSpendings = db.Spendings.Sum(x => x.AmountOfMoneySpent)
};
var result = new {
TotalIncomes = totalIncomesAndSpendings.TotalIncomes,
TotalSpendings = totalIncomesAndSpendings.TotalSpendings,
AccountBalance = totalIncomesAndSpendings.TotalIncomes - totalIncomesAndSpendings.TotalSpendings
};
我希望在一次交易中被查询
您可以将其打包在TransactionScope
:
using (var transaction = new TransactionScope())
{
// ...
}