2016-11-15 30 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"