Using Entity Framework 4.1 Code First I have two objects with a many-to-many relationship:
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; }
}
I want to count the most common Tags applied to Articles. How do I do this in LINQ?
I tried the below code which only ordered the Tags:
var tagsFromDb = db.Tags
.GroupBy(q => q.UrlSlug)
.OrderByDescending(gp => gp.Count())
.Select(g => g.FirstOrDefault());
If I understand right you have a many-to-many relationship between articles and tags but the navigation property on the tag side is not exposed (there is no
ICollection<Article>inTag). I think in this case you have to start from the articles to get all used tags along with the information how often they are used in the articles:If you want all tags sorted descending, call
If you just want the tag which is most often used in the articles, call
In both cases the result is a collection/single object of an anonymous type which has the
TagandCountas members. If you just want the tag(s) and are not interested in theCountanymore you can project before applyToListorFirstOrDefault:tagQuery.Select(anonymous => anonymous.Tag).....Edit
Just saw the Edit in your question. Now, when you have an
Articlecollection in theTagentity it is easier: