2016-09-07 54 views
-3

無法將此代碼轉換爲LINQ並預覽到數據網格視圖。將SQL代碼轉換爲LINQ - 分組依據和總計

我已經看過this答案,但它並沒有幫助我

select tbl_user.id,tbl_user.name,tbl_user.family, sum(tbl_price.price) 
     from tbl_user,tbl_price 
     where tbl_user.id=tbl_price.user_id_fk 
     group by tbl_user.name+''+tbl_user.family,tbl_user.id,tbl_user.name,tbl_user.family 

請幫我把這段代碼轉換到LINQ

+0

那麼,你試圖做什麼? – tym32167

+2

自己做一個嘗試,並回來你試過,不工作... https://stackoverflow.com/questions/12238423/linqpad-convert-sql-to-linq-command –

+0

我希望每個客戶的購買數量是 – user6805346

回答

0

你基本上需要連接兩個表,組由結果UserId和 針對用戶的每個項目在Price屬性值上調用Sum方法。

像這樣的事情

var usersWithTotalPrice = (from a in db.Users 
          join b in db.UserPrice on a.UserId equals b.UserId 
          select new { UserId = a.UserId, 
             FamilyName = a.Name + " " + a.FamilyName, 
             Price = b.Price} 
         ).GroupBy(f => f.UserId, items => items, (a, b) => new 
            { 
              UserId = a, 
              FamilyName = b.FirstOrDefault().FamilyName , 
              Price = b.Sum(g=>g.Price) 
            } 
         ).ToList(); 

usersWithTotalPrice變量將是一個UserIdFamilyNamePrice財產每個項目的集合。我使用匿名投影。如果你有一個視圖模型,你可以使用它。

public class UserWithPrice 
{ 
    public int Id { set;get;} 
    public string FamilyName { set;get;} 
    public decimal Price { set;get;} 
} 

和使用,在突出部分

var usersWithTotalPrice = (from a in db.Users 
          join b in db.UserPrice on a.UserId equals b.UserId 
          select new { UserId = a.UserId, 
             FamilyName = a.Name + " " + a.FamilyName, 
             Price = b.Price} 
         ).GroupBy(f => f.UserId, items => items, (a, b) => 
            new UserWithPrice 
            { 
              Id = a, 
              FamilyName = b.FirstOrDefault().FamilyName , 
              Price = b.Sum(g=>g.Price) 
            } 
         ).ToList(); 

更新你的實體/ Dbset /物業基於您定義名稱。

+0

非常感謝。正確的答案是 – user6805346

0

你甚至不需要爲此使用linq。其實你可以使用datatable,並將gridview的數據源設置爲該數據表。

public void LoadData() 
     { 
      DataTable dt = new DataTable(); 
      using (var conn = new SqlConnection("your connection string here")) 
      { 
       using (var cmd = conn.CreateCommand()) 
       { 
        conn.Open(); 

        //set the command up as a select 
        cmd.CommandText = "select tbl_user.id,tbl_user.name,tbl_user.family, sum(tbl_price.price) "+ 
        "from tbl_user, tbl_price " + 
        "where tbl_user.id = tbl_price.user_id_fk " + 
        "group by tbl_user.name + '' + tbl_user.family,tbl_user.id,tbl_user.name,tbl_user.family"; 

        using (SqlDataAdapter a = new SqlDataAdapter(cmd)) 
        { 
         a.Fill(dt); 
        } 

        //set the datasource of the gridview to the loaded table. The gridview will now display the data of your select statement. 
        dgvActivity.DataSource = dt; 

       } 
      } 
     }