简体   繁体   中英

How can I transform this SQL query to LINQ?

How can I transform this SQL query to 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'.

Does anybody have an Idea?

Edit #1: I forgot to mention the relationships between the entities. Every ExpenseGroup has many Expenses , and every Expense has many BudgetItems .

So, 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).

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. 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)
                   };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM