如何将此SQL查询转换为LINQ?
C
到目前为止,我已经提出了这一行:
SELECT eg.Name Name, sum(bi.PlannedAmount) Amount
FROM BudgetItem bi, Expense e, ExpenseGroup eg
WHERE Discriminator = 'ExpenseItem' AND
bi.ExpenseId = e.Id AND
e.ExpenseGroupId = eg.id AND
bi.MonthlyBudgetId = 1
GROUP BY eg.Name
但我仍然无法弄清楚用什么表达来添加' bi.MonthlyBudgetItem = 1'。
有人有想法吗?
编辑#1: 我忘了提到实体之间的关系。每个 ExpenseGroup 都有许多费用,每个费用都有许多 BudgetItems 。
所以,ExpenseGroup =>费用=> BudgetItems
编辑#2: 我使用Entity Framework,每个ExpenseGroup都有一个Expense对象集合(每个Expense都有一个ExpenseGroup对象),每个Expense都有一个BudgetItem对象集合(每个BudgetItem对象都有一个Expense对象)。
答案 0 :(得分:0)
我想这样的事情应该这样做:
var result = context
.ExpenseGroups
.Where(x => x.Discriminator == 'ExpenseItem' &&
x.bi.ExpenseId == e.Id &&
x.e.ExpenseGroupId == eg.id &&
x.bi.MonthlyBudgetId == 1)
.GroupBy(eg => eg.Id, (s) => new { Name = s.Name, Amount = s.Expenses.SelectMany(e => e.Items).Sum(i => i.PlannedAmount) })
.ToList();
答案 1 :(得分:0)
类似于此......
var result = (from g in context.ExpenseGroups
where g.Expense.BudgetItem.MonthlyBudgetId == 1
select g)
.GroupBy(eg => eg.Id, (s) => new { Name = s.Name, Amount = s.Expenses.SelectMany(e => e.Items).Sum(i => i.PlannedAmount) })
.ToList();
或
var result = context.ExpenseGroups
.Where(g => g.Expense.BudgetItem.MonthlyBudgetId == 1)
.GroupBy(eg => eg.Id, (s) => new { Name = s.Name, Amount = s.Expenses.SelectMany(e => e.Items).Sum(i => i.PlannedAmount) })
.ToList();
答案 2 :(得分:0)
您实际上在SQL查询中执行inner join
,因此在您的linq查询中也是如此。这应该有效: -
var result = from bi in context.BudgetItem
join e in context.Expense
on bi.ExpenseId equals e.Id
where bi.MonthlyBudgetId == 1
join eg in ExpenseGroup
on e.ExpenseGroupId equals eg.id
group new { bi, eg } by eg.Name into g
select new
{
Name = g.Key,
Amount = g.Sum(x => x.bi.PlannedAmount)
};