GroupBy中的字符串连接

时间:2016-04-22 14:48:43

标签: c# entity-framework linq-to-entities npgsql

以下查询无效,因为String.Join无法翻译。

PostgreSQL虽然具有string_agg(expression, delimiter)功能。

无论如何从Linq使用它?

var vwTourWithCategorieses = Context.Tours
                .Join(Context.TourCategories, t => t.TourId, tc => tc.TourId,
                    (t, tc) => new { t.TourId, t.Name, tc.CategoryId})
                .Join(Context.Categories, x => x.CategoryId, c => c.CategoryId,
                    (x, c) => new { x.TourId, TourName = x.Name, CategoryName = c.Name})
                .GroupBy(x => new { x.TourId, x.TourName },
                    (key, c) => new VwTourWithCategories
                    {
                        TourId = key.TourId,
                        Name = key.TourName,
                        Categories = string.Join(",", c.Select(i => i.CategoryName))
                    })
                .ToList();

1 个答案:

答案 0 :(得分:0)

是的,不幸的是,EF不支持String.Join,但我认为您可以在实现查询后将您希望使用Linq的结果投影到对象:

var query= Context.Tours
            .Join(Context.TourCategories, t => t.TourId, tc => tc.TourId,
                (t, tc) => new { t.TourId, t.Name, tc.CategoryId})
            .Join(Context.Categories, x => x.CategoryId, c => c.CategoryId,
                (x, c) => new { x.TourId, TourName = x.Name, CategoryName = c.Name})
            .GroupBy(x => new { x.TourId, x.TourName }).ToList()


var result=query.Select( g=> new VwTourWithCategories
                {
                    TourId = g.Key.TourId,
                    Name = g.Key.TourName,
                    Categories = string.Join(",", g.Select(i => i.CategoryName))
                });

如果您想查看支持的所有CLR方法,可以查看link

更新

如果您使用navigation properties,您的查询可能会更简单。我认为这是一个多对多的关系,所以你可以这样做:

var query= Context.Tours.Select(t=> new 
                                    {
                                      t.TourId, 
                                      t.Name,
                                      CategoryNames = t.TourCategories.Select(tc=>tc.Category.Name)
                                    } 
                               ).ToList();

var result=query.Select( g=> new VwTourWithCategories
                {
                    TourId = g.Key.TourId,
                    Name = g.Key.TourName,
                    Categories = string.Join(",", g.Select(i => i.CategoryName))                 
                });