2013-07-31 61 views
0

如何將此SQL查詢轉換爲LINQ表達式?對LINQ表達式的SQL查詢

select NoteDate, SUM(DurationInHours) from Note 
where IDUser = '2933FB9C-CC61-46DA-916D-57B0D5EF4803' and 
     NoteDate > '2013-07-01' 
group by NoteDate 

我嘗試過,但沒有奏效

var lastMonth = DateTime.Today.AddMonths(-1); 
var userNotes = GetNotesByUser(idUser); 
var b = from note in userNotes 
     group note by new {note.IDUser, note.NoteDate, note.DurationInHours} into g 
     where g.Key.NoteDate > lastMonth 
     select new {g.Key.NoteDate, TotalHours = g.Sum(a => a.DurationInHours)} 
+1

那你試試? – algreat

+0

這是學習LINQ查詢的好地方。 http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b –

+0

var lastMonth = DateTime.Today.AddMonths(-1); var userNotes = GetNotesByUser(idUser); VAR B =從音符在userNotes 組通過新的{note.IDUser,note.NoteDate,note.DurationInHours} 注入克 其中g.Key.NoteDate> lastMonth 選擇新的{g.Key.NoteDate,TotalHours = g.Sum(a => a.DurationInHours)} 我試過了,但沒有工作。我看到這個例子@CamBruce,但我有一些緊迫感。我用更多的時間研究它!謝謝。 – gog

回答

3
var id = new Guid("2933FB9C-CC61-46DA-916D-57B0D5EF4803"); 
var date = new DateTime(2013, 7, 1); 

var query = from n in db.Notes 
      where n.IDUser == id && n.NoteDate > date 
      group n by n.NoteDate into g 
      select new { 
       NoteDate = g.Key, 
       Sum = g.Sum(x => x.DurationInHours) 
      };