2017-02-13 52 views
0

我想一些SQL代碼轉換爲C#中的LINQ:轉換SQL的LINQ C#

SELECT Username, Count(Ticket.TicketId) as 'Tickets Completed' 
FROM Ticket 
INNER JOIN TicketStatus ON Ticket.TicketStatusID = TicketStatus.TicketStatusID 
INNER JOIN Membership ON Ticket.CompletedBy = Membership.UserId 
WHERE Ticket.ClosedDate >= @StartDate 
     and Ticket.ClosedDate <= @EndDate 
GROUP BY Username 
ORDER BY 'Tickets Completed' DESC 

,顯示

Paul 6 
Mike 4 
Donna 3 
Elliot 2 

我試圖用Linqer這讓這更復雜,並沒有回報任何結果:

var query = from Ticket in data.Tickets 
       join Membership in data.Memberships on new { CompletedBy = Guid.Parse(Ticket.CompletedBy.ToString()) } equals new { CompletedBy = Membership.UserId } 
       where 
        Ticket.ClosedDate >= StartDate && 
        Ticket.ClosedDate <= EndDate 
       group new { Membership, Ticket } by new 
       { 
        Membership.Username 
       } into g 
       orderby 
        "Tickets Completed" descending 
       select new 
       { 
        Username = g.Key.Username, 
        Completed = g.Count(p => p.Ticket.TicketID > 0) 
       }; 

您的幫助,將不勝感激。

感謝

+0

你確定數據不是空的嗎?你在使用ORM嗎? –

回答

1

假設CompletedByUserId列在數據庫中都uniqueidentifier,你應該不需要做任何類型轉換。

var query = from t in db.ticket 
     join ts in db.ticketStatus 
     on t.TicketStatus.ID equals ts.TicketStatusID 
     join m in db.Membership 
     on t.CompletedBy equals m.UserId 
     where t.ClosedDate >= startDate 
      && t.closedDate <= endDate 
     group t by m.UserName into tGroup 
     order by tGroup.Count(t=> t.TicketId) decending 
     select new { 
      UserName = tGroup.Key, 
      TicketCount = tGroup.Count() 
     }; 
+0

爲什麼不只是用m.UserName來分組?它也應該是'tGroup.Count()'。 – juharr

+0

更新了代碼..謝謝。有一箇舊的答案答案仍然執行 –

+0

這是完美的謝謝你。我一直在撓頭約4個小時,你在4分鐘內解決了它!再次感謝你。 – Belliez