Linq 实体框架中的多对多关系计数

Linq 实体框架中的多对多关系计数,linq,entity-framework,Linq,Entity Framework,首先使用Entity Framework 4.1代码,我有两个具有多对多关系的对象: public class Article { public int ID { get; set; } public string Title { get; set; } public string Description { get; set; } public ICollection<Tag> Tags { get

首先使用Entity Framework 4.1代码,我有两个具有多对多关系的对象:

 public class Article  
    {
        public int ID { get; set; } 
        public string Title { get; set; } 
        public string Description { get; set; }
        public ICollection<Tag>  Tags { get; set; }
}

 public class Tag
        { 
            [Key]
            public string UrlSlug { get; set; }
            public string Name { get; set; }
            public ICollection<Article> Articles { get; set; }
}

如果我理解正确,您在文章和标记之间有多对多关系,但是标记端的导航属性没有公开(在
标记
中没有
ICollection
)。我认为,在这种情况下,您必须从文章开始获取所有已使用的标记以及它们在文章中使用频率的信息:

var tagQuery = db.Articles
    .SelectMany(a => a.Tags)          // flat enumeration of all used tags
    .GroupBy(t => t, (k, g) => new    // k = key = Tag, g = group of same tags
    {
        Tag = k,                      // the tag
        Count = g.Count()             // how often does it occur in the articles
    })
    .OrderByDescending(g => g.Count); // most used tags first
如果您希望所有标签按降序排序,请调用

var tagList = tagQuery.ToList();
如果你只是想要文章中最常用的标签,请致电

var mostUsedTag = tagQuery.FirstOrDefault();
在这两种情况下,结果都是一个匿名类型的集合/单个对象,其成员为
标记
计数
。如果您只需要标记,而对计数不感兴趣,则可以在应用
ToList
FirstOrDefault
之前进行投影:
tagQuery。选择(anonymous=>anonymous.tag)…

编辑

刚刚看到你问题中的编辑。现在,如果在
标记
实体中有
文章
集合,则更容易:

var tagQuery = db.Tags
    .Select(t => new
    {
        Tag = t,                      // the Tag
        Count = t.Articles.Count()    // just count the number of artices
                                      // the tag is used in
    })
    .OrderByDescending(x => x.Count); // most used tags first
var tagQuery = db.Tags
    .Select(t => new
    {
        Tag = t,                      // the Tag
        Count = t.Articles.Count()    // just count the number of artices
                                      // the tag is used in
    })
    .OrderByDescending(x => x.Count); // most used tags first