【问题标题】:LINQ Query to retrieve multiple levels of relational data用于检索多级关系数据的 LINQ 查询
【发布时间】:2009-08-14 04:39:40
【问题描述】:

我刚刚开始使用 asp.net mvc,我想知道如何从 from 子句中指定的实体获取超过一层的关系数据。以如下领域模型为例:

一个博客有很多帖子。帖子有很多cmets。

如何编写 LINQ 查询以将实体返回到 Blog.Posts.Comments 级别?

我想出的唯一(不是那么优雅)的解决方案是使用 LINQ 查询来获取博客和帖子,然后使用 foreach 来获取 cmets。

var blog = (from b in _db.BlogSet.Include("Posts")
            select b);

foreach (Post p in blog.Posts)
{
    var comments = (from c in _db.CommentSet
                    where c.PostId = p.Id
                    select c);

    p.Comments = comments;

}

【问题讨论】:

    标签: asp.net-mvc linq


    【解决方案1】:

    一个博客有很多帖子。帖子有很多cmets。 如何编写 LINQ 查询以将实体返回到 Blog.Posts.Comments 级别?

    我相信,您可以执行以下操作来实现此目的:

    var blog = (from b in _db.BlogSet.Include("Posts.Comments")
                select b);
    

    在这种情况下,对于每个博客,都将获取帖子及其 cmets。

    马克

    【讨论】:

    • 如果我能投票更多,我会的!它适用于我的 4 个级别 :o)
    【解决方案2】:

    你可以只使用两个 from 语句:

    var comments=from post in blog
                 from comment in blog.comments
                 where comment.PostId==post.Id
                 select comment;
    

    【讨论】:

    • 很高兴知道这一点。当需要包含多个嵌套实体时,它会派上用场。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多