2017-08-17 143 views
0
select 
    t.Ticketid, t.subject, t.createdby, 
    count(TicketConversationId) as counts 
from 
    dbo.ticket t 
join 
    dbo.TicketConversation tc on t.ticketid = tc.ticketid 
group by 
    t.Ticketid, t.subject, t.createdby 

代碼:如何下面的SQL查詢轉換爲LINQ查詢在C#

var Result = from t1 in Tickets 
      join t2 in TicketConversations on t1.TicketId equals t2.TicketId 
      select new { t1.TicketId, t1.Subject , comments = t2.TicketConversationId }; 
+1

請爲提供一些LINQ嘗試你正在嘗試做 –

+0

還有你是什麼數使用? EF? –

+0

是的,它使用的是EF –

回答

1

好所以要加計數和分組爲您的查詢使用GroupBy

var result = from t1 in Tickets 
      join t2 in TicketConversations on t1.TicketId equals t2.TicketId 
      group t2.TicketConversationId by new { t.Ticketid, t.Subject, t.createdby } into g 
      select new { 
       t1.TicketId, 
       t1.Subject , 
       t1.CreatedBy, 
       Count = g.Count() }; 

請注意,在使用EF時,如果您正確定義了Navigation Properties,則不需要明確寫入連接,而只需要t1.Conversations.Count()或類似。


因爲所有你需要的是來計算記錄在t2匹配,您可以使用group join

var result = from t1 in Tickets 
      join t2 in TicketConversations on t1.TicketId equals t2.TicketId into con 
      select new { 
       t1.TicketId, 
       t1.Subject, 
       t1.CreatedBy, 
       Count = con.Count() 
      }; 
+0

感謝您解決了問題 –

+0

@SukhenduChakraborty - 如果這有助於您解決問題,請考慮將問題標記爲已解決 –