2017-04-07 35 views
0

给定以下返回博客帖子的方法,它的父级Blog对象以及该博客文章的注释列表;我试图确定在这种方法中是否有办法在评论列表中返回每条评论的评论回复列表。Linq to EF Include子列表列表

这里是类

public class Comment 
{ 
    [Key] 
    public int CommentId { get; set; } 

    //[ForeignKey("BlogPost")] 
    //[Index("IX_BlogPostIndex", 1, IsClustered = false, IsUnique = false)] 
    public int BlogPostId { get; set; } 

    public BlogPost BlogPost { get; set; } 

    [Required] 
    public string CommentText { get; set; } 
    [Required] 
    public DateTime CommentPostTime { get; set; } 

    public List<Reply> CommentReplies { get; set; } 


    [Required]  
    public string UserFullName { get; set; } 
} 

public class Reply 
{ 
    [Key] 
    public int ReplyId { get; set; } 

    [Required] 
    public string ReplyText { get; set; } 

    [Required] 
    public UserProfile MemberProfile { get; set; } 

    [ForeignKey("Comment")] 
    [Index("IX_CommentIndex", 1, IsClustered = false, IsUnique = false)] 
    public int CommentId { get; set; } 

    public Comment Comment { get; set; } 
    [Required] 
    public DateTime ReplyPostTime { get; set; } 


} 

而且方法

public BlogPost GetBlogPostById(int blogPostId) 
{ 
    return _db.BlogPosts.Where(e => e.BlogPostId == blogPostId) 
         .Include(e => e.Comments) 
         .Include(e => e.Blog) 
         .FirstOrDefault(); 
} 

我可以通过此方法返回的对象迭代和检索的答复,但我相信一定有办法,使用LINQ ,在这个方法中做,所以它们是返回对象的一部分,而不是运行另一种方法来做到这一点。

+1

您可以提供更多关于评论回复如何表示的信息吗?没有看到关系怎么不能为它写一个查询。 – 1283822

+0

将类定义添加到OP – dinotom

+0

我个人会在您的评论模型中使用ICollection而不是List,以及使用虚拟关键字在前面以及评论注释的前面为您的答复模型 – Edward

回答

0

如果“答复”是评论导航属性,您可以添加与现有查询的包括像这样:

.Include("Comments.Replies") 

此作品为包括你,只是更容易包含嵌套以同样的方式导航属性

+0

@Alex ...伟大的东西,我从来不知道你可以用这种方式写一个字符串包括。 – dinotom