Search code examples
c#asp.net.netentity-frameworkautomapper

OrderByDescending by child elements


I have two entities:

Blog:

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

Post:

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

...and I have two view models:

BlogVm:

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; }

As you can see they are the same.

I would like to get only blogs with at least 3 posts and take only 3 newest posts. Moreover, I would like to OrderByDescending Post.Published.

For mapping, I'm using AutoMapper.

I was trying something like this,s but the code does not work as I expected.

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

I'm getting an error message:

"System.ArgumentException: 'At least one object must implement IComparable.'"


Solution

  • at the moment you're asking it to order the Blogs by each blog's ordered posts, which... doesn't make sense. You could perhaps order the Blogs by their most recent publish date, and separately order each Blog's .Posts by their publish date descending?

    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));
    }