I’m trying to create a query between 2 tables that are defined as following
public class Article
{
public long ID { get; set; }
public int Language { get; set; }
public string? Title { get; set; }
public virtual ICollection<Tag>? Tags { get; set; }
}
public class Tag
{
public long ID { get; set; }
public string? Description { get; set; }
public virtual int Language { get; set; }
public string? Name { get; set; }
public virtual ICollection<Article>? Articles { get; set; }
}
What I like to do is to have the list of tags for a Language with a count of the articles for each tag. For example, I create an article with this code
Article a1 = new Article()
{
ID = 1,
Language = 1,
Body = "B1",
Title = "Title1",
Tags = new Tag[] {
new Tag()
{
ID = 1,
Language = 1,
Name = "L1",
},
new Tag()
{
ID = 2,
Language = 1,
Name = "L2"
}
}
};
Then, I add another Article with the same tags. What I expect is to have a query that returns to me a list like this one:
| TagId | Tag | Count |
|---|---|---|
| 1 | L1 | 2 |
| 2 | L2 | 2 |
The function I wrote is the following
Expression<Func<Tag, bool>> fnz = r => r.Language == lang;
List<LanguageTag> list = context.Tags.Where(fnz)
.GroupBy(t => new { t.Language, t.Name })
.Select(
r => new LanguageTag()
{
Language = r.Select(a => a.Language).FirstOrDefault(),
TagId = r.Select(a => a.ID).FirstOrDefault(),
TagName = r.Select(a => a.Name).FirstOrDefault(),
TagsCount = r.Select(a => a.Articles).Count()
}).ToList();
With this query, the result is that each Tag has a count equal to 1. How can I count the articles from each tag?
>Solution :
It seems to me you don’t need a ‘group by’ at all. Since you have the required relationships and also you don’t require anything from the Articles table the below query should work for you.
const reuult = context.Tags.Where(fnz)
.Select(r=> new LanguageTag {
Language = r.Language),
TagId = r.ID,
TagName = r.Name,
TagsCount = r.Articles.Count()
}).ToList();