2016-09-28 83 views
2

那是我的實體模型LINQ到實體GROUPBY和concatinate列

public class Warning 
     { 
      public int ID { get; set; } 
      public string WarningCId { get; set; } 
      public int WarningYearCounter { get; set; } 
      public string NavalDepartment { get; set; } 
      public string MiscellaneousInfo { get; set; } 
      public EmergencyType EmergencyType { get; set; } 
      public WarningType WarningType { get; set; } 
      public DateTime IssuedDate { get; set; } 
      public DateTime StartDate { get; set; } 
      public DateTime? EndDate { get; set; } 
      public string WarningMessage { get; set; } 
      public string WarningInfo { get; set; } 
      public bool Active { get; set; } 
      public string Status { get; set; } 
     } 

這就是我的倉庫

public class WarningRepository :IWarningRepository 
    { 
     private ApplicationDbContext _context { get; set; } 

     public WarningRepository (ApplicationDbContext context) 
     { 
      _context = context; 
     } 


    } 

我想groupby警告上startDate.Year(這是active == true並連接其列WarningYearCounter(類似於MySQL中的group_concat像這樣

Year Warning 
2014 1,5,6,7 
2015 6,8,9,0 

查詢:

_context.Warnings.Where(w => w.Active == true).GroupBy(w => w.StartDate.Year) 
+1

什麼阻止你添加它? – kiziu

+0

那麼你提供的查詢有什麼錯誤? – decPL

+0

@kiziu我不知道如何連接列linq到實體 –

回答

6

這聽起來像你想要做這樣的事情。

var results = (from w in _context.Warnings 
       where w.Active 
       group w.WarningYearCounter by w.StartDate.Year into grp 
       select grp) 
       .AsEnumerable() 
       .Select(g => new 
       { 
        Year = g.Key, 
        Warning = string.Join(",", g) 
       }); 

字符串連接是最好的數據庫之外完成的,所以在使用的AsEnumerable。另外,我只想對將被轉換爲SQL的部分使用查詢語法,然後切換到將在內存中完成的部分的方法語法,但是如果您願意,可以將其全部轉換爲方法或查詢語法。

+0

好的解決方案,但它是WarningYearCounter沒有ID – Fredrik

+0

@FredrikRedin良好的捕獲。固定。 – juharr

+0

@juharr非常感謝!它工作:) –

4

如果您希望EF Linq-To-SQL生成一條生成這些結果的SQL語句,我不相信這是可能的。但你可以得到非常接近:

public void GetWarningsGroup(IEnumerable<Warning> warnings) 
{ 
    var result = warnings 
     //Only Active warnings 
     .Where(w => w.Active) 
     //Grouped By year - Selecting the WarningYearCounter 
     .GroupBy(w => w.StartDate.Year, w => w.WarningYearCounter) 
     //Force Linq-To-SQL execution 
     .ToList() 
     //Finally concatenate the WarningYearCounter into the result 
     .Select(g => new Tuple<int, string>(g.Key, string.Join(",", g))); 
}