如何通过加入分组 Entity Framework
How to groupby with join in Entity Framework
在我的项目中,我对 Entity Framework 使用 code-first 方法。
我有两个表:
Tags
: 身份证、姓名
Post
: ID, 标题, Body, List<tag>
标签
每个post可以有一些标签,有些标签会重复几个post,这些表之间的关系是many-to-many.
public class post
{
public int Id { get; set; }
public int Title { get; set; }
public int Body { get; set; }
public ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int Id { get; set; }
public int Name { get; set; }
public ICollection<Post> Posts { get; set; }
}
我用这个代码但是不行:
var tags = db.posts.GroupBy(x => x.tags.Select(c => c.name)).Take(10).ToList();
我想获得前 10 个标签,但我做不到。
我想通过 EF 完成而不是 Linq
我在网上搜索过,没有找到类似的问题。
谢谢。
尝试:
var query = (from t in ctx.Tags.Include("Posts")
orderby t.Posts.Count() descending
select t).Take(10).ToList();
在我的项目中,我对 Entity Framework 使用 code-first 方法。
我有两个表:
Tags
: 身份证、姓名Post
: ID, 标题, Body,List<tag>
标签
每个post可以有一些标签,有些标签会重复几个post,这些表之间的关系是many-to-many.
public class post
{
public int Id { get; set; }
public int Title { get; set; }
public int Body { get; set; }
public ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int Id { get; set; }
public int Name { get; set; }
public ICollection<Post> Posts { get; set; }
}
我用这个代码但是不行:
var tags = db.posts.GroupBy(x => x.tags.Select(c => c.name)).Take(10).ToList();
我想获得前 10 个标签,但我做不到。
我想通过 EF 完成而不是 Linq
我在网上搜索过,没有找到类似的问题。
谢谢。
尝试:
var query = (from t in ctx.Tags.Include("Posts")
orderby t.Posts.Count() descending
select t).Take(10).ToList();