【问题标题】:OrderByDescending by child elementsOrderByDescending 按子元素
【发布时间】:2017-12-22 13:00:03
【问题描述】:

我有两个实体: 博客:

public int Id { get; set; }
public string Name { get; set; }
public List<Post> Posts { get; set; }

帖子:

public int Id { get; set; }
public string Name { get; set; }
public DateTime Published { get; set; }

我有两个视图模型: 博客虚拟机:

public int Id { get; set; }
public string Name { get; set; }
public List<PostVm> Posts { get; set; }

PostVm:

public int Id { get; set; }
public string Name { get; set; }
public DateTime Published { get; set; }

如您所见,它们是相同的。

我只想获取至少 3 篇文章的博客,并且只获取 3 篇最新文章。此外,我想OrderByDescending Post.Published。

对于映射,我使用的是 AutoMapper。

我正在尝试这样的事情,但代码没有按预期工作。

var blogs = _context.Blogs.Include(x => x.Posts)
                .Where(x.Posts.Count >= 4)
                .ProjectTo<BlogVm>()
                .OrderByDescending(x => x.Posts.OrderByDescending(y => y.Published)).ToList();

我收到一条错误消息:

"System.ArgumentException: '至少一个对象必须实现 IComparable。'"

【问题讨论】:

    标签: c# asp.net .net entity-framework automapper


    【解决方案1】:

    目前您要求它按每个博客的已排序帖子订购Blogs,这...没有意义。您或许可以按最近的发布日期Blogs 进行排序,并单独按每个Blog.Posts 按发布日期降序排序? p>

    var blogs = _context.Blogs.Include(x => x.Posts)
                    .Where(x.Posts.Count >= 4)
                    .ProjectTo<BlogVm>()
                    .OrderByDescending(x => x.Posts.Max(y => y.Published)).ToList();
    
    foreach(var blog in blogs) {
        blog.Posts.Sort((x,y) => y.Published.CompareTo(x.Published));
    }
    

    【讨论】:

    • 为什么不是quickblogs.ForEach(x =&gt; x.Posts.Sort((y, z) =&gt; z.Date.CompareTo(y.Date)));
    • @MUT k;现在:以什么客观的方式是一种改进? IMO ForEach 方法被过度使用。
    【解决方案2】:

    你可以这样试试;

    var blogs = _context.Blogs.Include(x => x.Posts)
        .Where(x.Posts.Count >= 4)
        .ProjectTo<BlogVm>()
        .Select(x => new
        {
            Blog = x,
            //Take newly published 3 posts for per Blog
            RecentlyPosts = x.Posts.OrderByDescending(y => y.Published).Take(3)
        });
    

    另外,最好创建一个模型类来选择已知类型而不是匿名类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多