c# - linq lambda 多组连接

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

我正在尝试获取产品列表及其评级、评论和 View 。 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

我的类(class)看起来像这样——
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 group join 获取此信息,以便获得子集合。
IEnumerable<Product> _products = _context.Product.GroupJoin(_context.Rating, p=>p.id, r=>r.PID, (Product, Rating) => new Product(){
    //fill fields here
});

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

谢谢

最佳答案

而不是 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()
                                });

关于c# - linq lambda 多组连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47718494/

相关文章:

javascript - 在 javascript 中编写反函数?

c# - MVVM - 按钮命令绑定(bind)不起作用

C# For 循环保留未实例化变量中的值

python - ASP.NET MVC 上的 IronPython

c# - 如何测量 LINQ 查询的时间?

amazon-web-services - 从 AWS Lambda 发送 RabbitMQ 消息

java - 使用 Java 8 转换类

c# - grpc.core 的 Xamarin iOS native 链接失败

c# - 日期选择器 ASP.NET c# mvc4

c# - LINQ 获取特殊字符的最后位置