c# - 在 Entity Framework 中订购包含的实体的最佳方式?

标签 c# asp.net entity-framework asp.net-core entity

订购评论实体的最佳实践是什么?

 public async Task<IList<Post>> GetPosts() {
             var posts = _context.Posts
            .Include(u => u.User)
            .ThenInclude(p => p.Photos)
            .Include(c => c.Comments)   <---- THIS      
            .OrderByDescending(p => p.Created)
            .ToListAsync();

            return await posts;
        }

最佳答案

在返回帖子之前,您可以订购附加到每个帖子的评论:

var posts = await _context.Posts
                          .Include(u => u.User)
                          .ThenInclude(p => p.Photos)
                          .Include(c => c.Comments)         
                          .OrderByDescending(p => p.Created)
                          .ToListAsync();

foreach(var post in posts)
{
    post.Comments = post.Comments
                        .OrderBy(comment => comment.DateCreated)
                        .ToList();
} 

return posts;

我根据名为 DateCreated 的属性进行了上述排序。您必须将其更改为注释对象属性,您希望以此为基础进行排序。

关于c# - 在 Entity Framework 中订购包含的实体的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60988962/

相关文章:

c# - 有没有办法在Excel中找到一个范围内的范围?

javascript - 是否可以将 ASP.NET Web 应用程序上传到 VMware 上的虚拟 2008 服务器?

c# - Entity Framework 使用扩展方法抛出异常

c# - LINQ 查询仅使用 Entity Framework 计算的值

c# - json.net IValueProvider SetValue 抛出异常丢失

c# - Listview 中的 TextBox - 在 TextBox TextChanged 上获取 ListViewItem

带有服务器端 Url.Content 的 JavaScript 语法

javascript - 向 ASP.NET MVC JsonResult 添加无法解析的内容

c# - ODAC 12c 和 Entity Framework 6

c# - 为 C# 项目自动生成所有内联 XML 文档