2015-05-26 63 views
0

我想選擇一個SQL表和使用Linq到SQL,實體或對象的列分組(我真的不知道什麼。)我Linq有點新,可以使用一些幫助。代碼結構在我看來是直截了當的。當我不添加GroupBy方法時,它工作正常。順便說一下JT_Temp是一個實體模型。當我在下面運行我的代碼時,它會發生異常:無法從數據庫表中選擇記錄與分組使用Linq

實體或複雜類型'JT_Temp'不能在LINQ to Entities查詢中構造。

我試過this和各種計算器的解決方案,但他們似乎並沒有解決和適用於我的情況。

這裏是我當前的代碼:

//Goal: 
//SELECT EnvelopeCode, Branch_COA, AQ_COA, AQ_Branch, SUM(Amount), AQ_PostStatus FROM JT_Temp 
      //GROUP BY EnvelopeCode, Branch_COA, AQ_COA, AQ_Branch, AQ_PostStatus 

//var csvFilteredRecord = Context.JT_Temp.SqlQuery("SELECT * FROM JT_Temp").ToList<JT_Temp>(); 
// GROUP BY -- No go; Manual SELECT -- No go; 

      try 
      { 


       var csvFilteredRecord = (
        from c in Context.JT_Temp 
        group c by new 
        { 
         c.EnvelopeCode, 
         c.Branch_COA, 
         c.AQ_COA, 
         c.AQ_Branch, 
         c.AQ_PostStatus 
        } into i 
        select new JT_Temp 
        { 
         EnvelopeCode = i.Key.EnvelopeCode, 
         Branch_COA = i.Key.Branch_COA, 
         AQ_COA = i.Key.AQ_COA, 
         AQ_Branch = i.Key.AQ_Branch, 
         //TO-DO SUM(Amount), 
         AQ_PostStatus = i.Key.AQ_PostStatus 
        }).ToList(); 

       foreach (var Record in csvFilteredRecord) 
       { 
        Console.WriteLine(
          Record.EnvelopeCode 
          + Record.Branch_COA 
          + Record.AQ_COA 
          //+ Record.Amount 
          + Record.AQ_PostStatus 
         ); 
       } 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine("---------- " + e.Message); 
       Console.ReadLine(); 

      } 
+1

你看任何的LINQ的例子在MSDN [C#MSDN的LINQ GroupBy](https://msdn.microsoft.com/en-us/library/bb545971.aspx) – MethodMan

回答

1

你無法投射到JT_Temp。只需使用一個匿名對象。此外,沒有理由讓一個列表,所以我刪除了.ToList() 查詢語法:

var csvFilteredRecord = (
       from c in Context.JT_Temp 
       group c by new 
       { 
        c.EnvelopeCode, 
        c.Branch_COA, 
        c.AQ_COA, 
        c.AQ_Branch, 
        c.AQ_PostStatus 
       } into i 
       select new 
       { 
        EnvelopeCode = i.Key.EnvelopeCode, 
        Branch_COA = i.Key.Branch_COA, 
        AQ_COA = i.Key.AQ_COA, 
        AQ_Branch = i.Key.AQ_Branch, 
        //TO-DO SUM(Amount), 
        AQ_PostStatus = i.Key.AQ_PostStatus 
       }); 

方法的語法:

var csvFilteredRecord = Context.JT_Temp.GroupBy(k=> new 
    { 
    c.EnvelopeCode, 
    c.Branch_COA, 
    c.AQ_COA, 
    c.AQ_Branch, 
    c.AQ_PostStatus 
    }, 
    v=>v.Amount, 
    (k,v)=>new { 
    k.EnvelopeCode, 
    k.Branch_COA, 
    k.AQ_COA, 
    k.AQ_Branch, 
    k.AQ_PostStatus 
    Amount=v.Sum() 
    }); 
foreach (var Record in csvFilteredRecord) 
{ 
    Console.WriteLine(
    Record.EnvelopeCode 
    + Record.Branch_COA 
    + Record.AQ_COA 
    + Record.Amount 
    + Record.AQ_PostStatus 
); 
} 
+0

謝謝@Robert McKee。這工作。多虧了methodman。我會從那裏讀到關於分組的信息。 –