[英]Load Self Referencing Entity With EF Core 5.0 ( Just get Parents and their children in their navigation property )
我想實現一個評論系統,這是我的評論實體。
public class Comment
{
public int CommentId { get; set; }
public int? ParentId { get; set; }
public string Content { get; set; }
public DateTimeOffset DateCreated { get; set; }
public DateTimeOffset DateModified { get; set; }
public Comment Parent { get; set; }
public ICollection<Comment> Children { get; set; }
}
這是我在 Fluent 中的配置 API
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Comment>(comment =>
{
comment.HasKey(c => c.CommentId);
comment.HasIndex(c => c.ParentId);
comment.HasOne(c => c.Parent)
.WithMany(c => c.Children)
.HasForeignKey(c => c.ParentId);
});
}
一切正常,我可以使用此代碼加載所有具有層次結構的記錄(包括父項和子項)
List<Comment> comments = await _db.Comments.Include(c => c.Children)
.ToListAsync();
但是此代碼加載所有元素,例如子元素。 但我想加載所有的父母,然后加載他們的孩子,然后加載孫子和......
我在這種情況下使用此代碼
List<Comment> comments = await _db.Comments.Include(c => c.Children)
.Where(c => c.ParentId == null)
.ToListAsync();
這段代碼只是加載所有父母和他們的孩子,而不是孫子和更多的層次結構。
我應該如何編寫此查詢?
我找到了這種情況的解決方案。
public async Task<IActionResult> Index()
{
List<Comment> comments = await _db.Comments.AsNoTrackingWithIdentityResolution()
.Include(c => c.Children)
.ToListAsync();
// Structure Comments into a tree
List<Comment> commentsTree = comments.Where(c => c.ParentId == null)
.AsParallel()
.ToList();
return View(commentsTree);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.