2016-09-28 46 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))); 
}