linq lambda multiple group joins

时间:2017-12-08 16:33:17

标签: c# linq lambda linq-to-sql entity

我正在尝试获取产品列表及其评级,评论和观点。 PID是没有外键关系的产品ID列。

产品 -

Id  Name
1   P1
2   P2

评级 -

Id  PID Rating
1   1   5
2   1   4
3   2   3

评论 -

Id  PID Comment
1   1   Good
2   1   Average
3   2   Bad

观点 -

Id  PID View
1   1   500
2   1   200
3   2   10

我的课程看起来像这样 -

Public Class Product{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Rating> Ratings{ get; set; }
    public List<Comments> Comments{ get; set; }
    public List<Views> Views{ get; set; }
}

我正在尝试使用Linq组加入来获取此信息,以便我收集子项。

IEnumerable<Product> _products = _context.Product.GroupJoin(_context.Rating, p=>p.id, r=>r.PID, (Product, Rating) => new Product(){
    //fill fields here
});

但是如何将其他表分组到单个数据库查询中。

由于

2 个答案:

答案 0 :(得分:0)

您可以直接查找匹配项来构建GroupJoin对象,而不是Product

IEnumerable<Product> _products = _context.Product.Select(product => new Product() {
    Id = product.id,
    Name = product.name,
    Ratings = _context.Rating.Where(r => r.PID == product.id).ToList(),
    // ... other lists similar
});

正如评论中所指出的,上述查询可以为每个产品生成三个子查询。

如果您创建匿名对象来保存中间结果,则可以使用GroupJoin

var _products = _context.Product.GroupJoin(_context.Rating, p => p.id, r => r.PID, (p, rs) => new { p, rs })
                                .GroupJoin(_context.Comment, prs => prs.p.id, c => c.PID, (prs, cs) => new { prs.p, prs.rs, cs })
                                .GroupJoin(_context.View, prs => prs.p.id, v => v.PID, (prscs, vs) => new Product() {
                                    Id = prscs.p.id,
                                    Name = prscs.p.name,
                                    Ratings = prscs.rs.ToList(),
                                    Comments = prscs.cs.ToList(),
                                    Views = vs.ToList()
                                });

答案 1 :(得分:0)

你可以这样试试;

        var records = _context.Product
            .GroupJoin(_context.Ratings, p => p.Id, r => r.PID, (p, r) => new { Product = p, Ratings = r})
            .GroupJoin(_context.Comments, p => p.Product.Id, c => c.PID, (p, c) => new { p.Product, p.Ratings, Comments = c})
            .GroupJoin(_context.Views, p => p.Product.Id, v => v.PID, (p, v) => new { p.Product, p.Ratings, p.Comments, Views = v })
            .Select(p => new
            {
                Id = p.Product.Id,
                Name = p.Product.Name,
                Comments = p.Comments,
                Ratings = p.Ratings,
                Views = p.Views
            })
            .ToList().Select(x => new Product
            {
                Id = x.Id,
                Name = x.Name,
                Comments = x.Comments.ToList(),
                Ratings = x.Ratings.ToList(),
                Views = x.Views.ToList()
            }).ToList();