我试图制作一个类似Reddit的讨论板,其中一个帖子可以有多个评论,每个评论可以有多个评论,每个评论可以有多个评论,等等。
我将如何编写一个查询来返回一个特定的帖子,其中包括它的所有评论,以及所有评论的评论,等等?,我想使用.ThenInclude(),但这是不可能的,因为我不知道有多少嵌套的注释提前。
这是我目前拥有的内容,但它只检索对“邮报”的直接答复,并且没有嵌套的注释:
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; }
}DbContext:
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; }
}发布于 2021-02-25 21:56:42
考虑一下查询在SQL (而不是C#/LINQ )中的外观。因为这些关系是递归的,所以您需要显式地定义连接,因为很多层都需要预取。这就给您留下了任何其他层的缺失数据。或者,您可以使用由存储过程绑定的游标。不是的。相反,一个注释可以有一个指向其父注释的指针,但也可以有一个指向大多数父实体的外键(原始帖子)。然后,当您获得一个帖子的所有注释时,您可以作为一个平面数组检索所有注释,然后在c#中构建树(在SQL之外)。这应该更有表现力。
https://stackoverflow.com/questions/66376967
复制相似问题