如何将SQL转换为LINQ-to-SQL

时间:2012-07-11 06:34:13

标签: sql linq-to-sql

SELECT     Cities.CityName, Customers.CustomerName, SUM(Bills.Sarees)
FROM       Bills INNER JOIN
                      Customers ON Bills.CustomerID = Customers.CustomerID INNER JOIN
                      Cities ON Customers.CityID = Cities.CityID
Group by CustomerName, CityName

我试图将其设为如下....但我无法在

中插入group by子句
 var query = db.Bills.Join(db.Customers, c => c.CustomerID, p => p.CustomerID, (c, p) => new
            {
                c.Customer.CustomerID,
                c.Customer.CustomerName,
                c.Customer.City.CityName,
                c.Customer.Mobile1,
                c.Customer.Mobile2,
                c.Customer.Telephone,
                c.Customer.Email,
                c.Sarees
            });

1 个答案:

答案 0 :(得分:1)

看看你的SQL,我想你需要这样的东西:

var query = db.Bills
    .Join(db.Customers, b => b.CustomerID, c => c.CustomerID, (b, c) => new
    {
        b.Sarees,
        c.CustomerName,
        c.CityID
    })
    .Join(db.Cities, j => j.CityID, c => c.CityID, (j, c) => new 
    {
        j.Sarees,
        j.CustomerName,
        j.CityID,
        c.CityName
    })
    .GroupBy(o => new { o.CustomerName, o.CityName })
    .Select(o => new { o.Key.CityName, o.Key.CustomerName, Sum = o.Sum(i => i.Sarees) });