Linq to Entity Groupby和concatinate专栏

时间:2016-09-28 13:38:49

标签: c# entity-framework linq

这就是我的实体模型

 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中的{1}} 像这样

group_concat

查询:

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

2 个答案:

答案 0 :(得分: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)
              });

字符串连接最好在DB之外完成,因此使用AsEnumerable。此外,我只想对将要转换为SQL的部分使用查询语法,然后切换到将在内存中完成的部分的方法语法,但如果您愿意,可以将其全部转换为方法或查询语法。

答案 1 :(得分: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)));
}