[英]How to get specific number of rows when using Include method in entity framwork?
我有帖子和評論表。 我可以通過這個獲得帖子和評論:
List<Posts> posts = db.Posts.Include("Comments").ToList();
上面的代碼返回每個帖子的所有評論。 我想要兩件事:
您不能使用Include
方法來獲得您想要實現的目標。 在以下示例中,結果以匿名類型返回:
var postInfo = db.Posts.Select(p => new
{
Post = p,
Comments = p.Comments.Take(5),
TotalNumberOfComments = p.Comments.Count
})
每篇文章獲得5條評論:
var postWithComments = db.Posts.Select(x => new
{
Post = x,
Comments = x.Comments.Take(5),
CommentsCount = x.Comments.Count()
});
方法Take(5)
允許您僅使用內部數據加載5條注釋,方法Count()
僅獲取行數。
假設您有這樣的Post DTO / View模型/ POCO
public class PostDto
{
public string Title{ set; get; }
public int Id { set; get; }
public List<PostDto> Comments { set; get; }
public int TotalCommentCount { set; get; }
}
以下將獲得評論計數的所有帖子和最后5條評論。 如果需要,您可以更新OrderByDescending以傳遞另一個屬性(如插入時間戳等)
var posts = dbContext.Posts.
Select(s => new PostDto
{
Id = s.PostId,
Title= s.PostTitle,
TotalCommentCount = s.Comments.Count(),
Comments = s.Comments.OrderByDescending(f => f.Id).Take(5)
.Select(x => new PostDto
{
Id = x.CommentId,
Name = x.CommentText
}).ToList()
}).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.