我有两个实体:博客:
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; }
我有两个视图模型: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; }
正如你所看到的那样。
我想只获得至少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。'”
目前你要求它按每个博客订购的帖子订购Blog
s,这......没有意义。您可以按照最近的发布日期订购Blog
s,然后按发布日期降序单独订购每个Blog
的.Posts
?
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));
}
你可以这样试试;
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)
});
此外,最好创建一个模型类来选择已知类型而不是匿名类型。