[英]How can I transform this SQL query to LINQ?
How can I transform this SQL query to LINQ? 如何将该SQL查询转换为LINQ?
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
So far I've come up with this line: 到目前为止,我已经提出了这一行:
var result = context
.ExpenseGroups
.GroupBy(eg => eg.Id, (s) => new { Name = s.Name, Amount = s.Expenses.SelectMany(e => e.Items).Sum(i => i.PlannedAmount) })
.ToList();
But I still cannot figure out what expression to use to add 'bi.MonthlyBudgetItem = 1'. 但是我仍然不知道要使用什么表达式来添加'bi.MonthlyBudgetItem = 1'。
Does anybody have an Idea? 有人有主意吗?
Edit #1: I forgot to mention the relationships between the entities. 编辑1:我忘了提及实体之间的关系。 Every ExpenseGroup has many Expenses , and every Expense has many BudgetItems .
每个ExpenseGroup都有很多费用 ,每个Expense都有很多BudgetItems 。
So, ExpenseGroup => Expenses => BudgetItems 因此,ExpenseGroup => Expenses => BudgetItems
Edit #2: I'm using Entity Framework and every ExpenseGroup has a Collection of Expense objects (every Expense has a ExpenseGroup object), as well as every Expense has a Collection of BudgetItem objects (every BudgetItem object has a Expense object). 编辑2:我使用的是Entity Framework,每个ExpenseGroup都有一个Expense对象的集合(每个Expense都有一个ExpenseGroup对象),每个Expense都有一个BudgetItem对象的集合(每个BudgetItem对象都有一个Expense对象)。
I suppose something like this should do it: 我想应该这样做:
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();
Something similar to this... 与此类似...
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();
or 要么
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();
You are actually doing an inner join
in your SQL query, so do similarly in your linq query as well. 您实际上是在SQL查询中进行
inner join
联接,因此在linq查询中也是如此。 This should work:- 这应该工作:
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)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.