I have the following nested SQL Statement and i will to do the same using Lambda statement in C# How do i do it?
SQL:
SELECT board.*, (SELECT COUNT(*) from discussion_topic
WHERE TopicBoardID=board.BoardID) as TopicCount
FROM `discussion_board` as board
This is the structure of my 2 tables
Table Name: discussion_board
Fields:
BoardID
BoardName
BoardCreatedBy
BoardCreatedDate
Table Name: discussion_topic
Fields:
TopicID
TopicName
TopicCreatedBy
TopicCreatedDate
TopicBoardID
just 2 simple tables with no Forign Keys,
Thank you!
This will give you a new anonymous type which will have the board record and the count of discussion topics.
var result = dataContext.Board.Select(x => new {x, Count = x.DiscussionTopics.Count()});
You could simply use board.DiscussionTopics.Count();
on each record to get the count. No need to do the above really, if i understand your question correctly
UPDATE
If you have no foreign keys then this might do it
var result = dataContext.Board.Select(x => new {x, Count = dataContext.DiscussionTopics.Count(d => d.TopicBoardId == x.BoardID)});
from b in DataContext.Boards
select new {
BoardId = b.BoardID,
BoardName = b.BoardName,
BoardCreatedBy = b.BoardCreatedBy,
BoardCreateDate = b.BoardCreateDate,
TopicCount = Discussions.Count(d => d.TopicBoardId == b.BoardID)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.