【发布时间】:2021-02-25 21:52:03
【问题描述】:
我正在尝试创建一个类似于 Reddit 的讨论板,其中一个帖子可以有多个评论,每个评论可以有多个评论,每个评论可以有多个评论,等等。
我将如何编写查询以返回包含所有评论、所有评论的 cmets 以及所有评论的 cmets 等的特定帖子?我想过使用 .ThenInclude() 但这是不可能的,因为我不知道有多少嵌套的 cmets 提前。
这是我目前拥有的,但它只检索对帖子的直接回复,而不是嵌套的 cmets:
selected = await context.Posts
.Include(p => p.Author)
.Include(p => p.SavedBy)
.Include(p => p.HiddenBy)
.Include(p => p.UpvotedBy)
.Include(p => p.DownvotedBy)
.Include(p => p.Replies.Where(c => !c.HiddenBy.Contains(user)))
.ThenInclude(c => c.Author)
.Include(p => p.Replies)
.ThenInclude(c => c.SavedBy)
.Include(p => p.Replies)
.ThenInclude(c => c.HiddenBy)
.Include(p => p.Replies)
.ThenInclude(c => c.UpvotedBy)
.Include(p => p.Replies)
.ThenInclude(c => c.DownvotedBy)
.SingleAsync(p => p.Id == id);
型号:
public abstract class Entry
{
public Entry()
{
Replies = new List<Comment>();
SavedBy = new List<ApplicationUser>();
HiddenBy = new List<ApplicationUser>();
UpvotedBy = new List<ApplicationUser>();
DownvotedBy = new List<ApplicationUser>();
}
public int Id { get; set; }
public string Content { get; set; }
public DateTime DateCreated { get; set; }
public int Upvotes { get; set; }
public int Downvotes { get; set; }
public int VoteScore { get; set; }
public ApplicationUser Author { get; set; }
public ICollection<Comment> Replies { get; set; }
public ICollection<ApplicationUser> SavedBy { get; set; }
public ICollection<ApplicationUser> HiddenBy { get; set; }
public ICollection<ApplicationUser> UpvotedBy { get; set; }
public ICollection<ApplicationUser> DownvotedBy { get; set; }
}
public class Post : Entry
{
public string Title { get; set; }
}
public class Comment : Entry
{
public Entry RepliedTo { get; set; }
public Post Post { get; set; }
}
数据库上下文:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Entry> Entries { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
}
【问题讨论】:
标签: c# asp.net-mvc entity-framework .net-core entity-framework-core