2016-11-15 51 views
1

誰能幫我寫等價的SQL選擇組值的LINQ C#如何使用LINQ to SQL的

select 
COUNT(ot.UserId) as orderCount, SUM(ot.TotalAmount) as TotalAmount, 
MAX(u.UserName) as UserName, MAX(c.name) as ClientName 
from OrderTemplate ot 
join User u 
on u.userid = ot.UserId 
join Client c 
on u.ClientID = c.clientid 
group by ot.UserId 

我所做的是,

from ot in dbContext.OrderTemplates 
join user in dbContext.Users on ot.UserId equals user.UserID 
join client in dbContext.Clients on user.ClientID equals client.ClientID 
group ot by ot.UserId into g 
select new 
{ 
    //UserName = need to pick this from user table 
    //ClientName = need to pick this from client table 
    OrderCount = g.Count(), 
    TotalAmount = g.Sum(x=> x.TotalAmount) 
}; 

我可以」 t根據sql選擇值。

+1

「用戶名」的值是什麼? 「Max(u.Username)」實際上是什麼意思?那些是相同的用戶名?是一些'null'的值,然後你做'max'來得到那個不是? –

+0

是的,每個組的用戶名都是一樣的,所以我只需要選擇一個。 –

+0

另外在你的sql中,你正在用'UserId'打斷,但在'orderId'的linq中 –

回答

2

因此,如果用戶名和客戶端名稱是相同的(和actaully每個訂單都有一個客戶端和一個用戶)更好組由多個鍵:

from ot in dbContext.OrderTemplates 
join u in dbContext.Users on ot.UserId equals u.UserID 
join c in dbContext.Clients on u.ClientID equals c.ClientID 
group ot by new { ot.UserId, u.UserName, c.ClientName } into g 
select new 
{ 
    UserName = g.Key.UserName, 
    ClientName = g.Key.ClientName, 
    OrderCount = g.Count(), 
    TotalAmount = g.Sum(x=> x.TotalAmount) 
}; 

如果不是,或完全一樣,如果你想你的SQL然後在實例化匿名對象時代替具有多個屬性的密鑰:

Username = g.Max(item => item.UserName) // will just use string comparison to select the "max"