У меня есть 2 таблицы, Форумы и Сообщения.
Я хочу получить все поля Forums с новым дополнительным полем: считайте все сообщение, которые принадлежат этому форуму.
У меня есть это на данный момент:
var v =(from forum in Forums
join post in Posts on forum.ForumID equals post.Forum.ForumID
select new
{
forum, //Need to retrieve all fields/columns from forum
PostCount = //count all post that belong to this forum with a condition: count it only if post.Showit==1
}
).Distinct()
Думаю, вам нужно что-то вроде:
from forum in Forums
// ForumID part removed from both sides: LINQ should do that for you.
// Added "into postsInForum" to get a group join
join post in Posts on forum equals post.Forum into postsInForum
select new
{
Forum = forum,
// Select the number of shown posts within the forum
PostCount = postsInForum.Where(post => post.ShowIt == 1).Count()
}
Или (как указано в комментариях) вы можете поместить условие в вызов Count
- я всегда забываю, что это доступно: )
from forum in Forums
// ForumID part removed from both sides: LINQ should do that for you.
// Added "into postsInForum" to get a group join
join post in Posts on forum equals post.Forum into postsInForum
select new
{
Forum = forum,
// Select the number of shown posts within the forum
PostCount = postsInForum.Count(post => post.ShowIt == 1)
}
Другой альтернативой для фильтрации только "показанных" постов было бы сделать это в join:
from forum in Forums
join post in Posts.Where(post => post.ShowIt == 1)
on forum equals post.Forum into shownPostsInForum
select new
{
Forum = forum,
// Select the number of shown posts within the forum
PostCount = shownPostsInForum.Count()
}
Я считаю, что все это логически правильно, но я не знаю, как будет выглядеть SQL. ..
Если вы подключите форумы к сообщениям в конструкторе linqtosql, это создаст свойство отношения, которое можно будет запросить.
var query =
from f in db.Forums
select new
{
forum = f,
PostCount = f.Posts.Count(p => p.ShowIt == 1)
};