我有两个实体: 博客:
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();
我收到错误消息:
&#34; System.ArgumentException:&#39;至少有一个对象必须实现 。IComparable的&#39;&#34;
答案 0 :(得分:4)
此刻,您要求它按每个博客订购的帖子订购Blog
,这......没有意义。您可以按最近发布日期订购Blog
,然后单独按每个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));
}
发布日期下降?
lapply
答案 1 :(得分:1)
你可以这样试试;
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)
});
此外,最好创建一个模型类来选择已知类型而不是匿名类型。