2015-10-23 59 views
1

如何將這個SQL查詢轉換爲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 

到目前爲止,我想出了這條線:

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(); 

但我還是想不出用什麼表情添加「bi.MonthlyBudgetItem = 1」。

有沒有人有想法?

編輯#1: 我忘了提及實體之間的關係。每ExpenseGroup有很多費用,並且每費用有很多BudgetItems

所以,ExpenseGroup =>費用=> BudgetItems

編輯#2: 我使用實體框架和每個ExpenseGroup具有費用對象的集合(每費用有ExpenseGroup對象),以及因爲每個Expense都有一個BudgetItem對象集合(每個BudgetItem對象都有一個Expense對象)。

回答

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(); 
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(); 
0

你實際上是在做一個inner join您SQL查詢,所以在你的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) 
        }; 
+0

那麼你的問題解決了嗎? –