u936293
u936293

Reputation: 16234

Getting data of three levels of hierarchy

I want to develop a discussions application where there are a number of Forums. In each forum there can be many Threads. And in each thread, there can be a number of Posts. In SQL, I have the following four tables:

FORUMS

THREADS

POSTS

USERS

What is the best way of returning a list with the following columns of all the forums in the database (one row in the list corresponds to one row in FORUMS):

Thanks

Upvotes: 0

Views: 80

Answers (1)

lante
lante

Reputation: 7336

Something like:

var query = from f in context.Forums
            select new
            {
                Name = f.Name,
                Threads = f.Threads.Count(),
                Posts = f.Threads.Sum(t => t.Posts.Count()),
                LastThread = f.Threads.OrderByDescending(t => t.Id).First().Subject,
                LastPostSubmitter = f.Threads.SelectMany(t => t.Posts).OrderByDescending(p => p.SubmitterOn).First().Name,
                LastPostSubmitterTime = f.Threads.SelectMany(t => t.Posts).OrderByDescending(p => p.SubmitterOn).First().SubmitterOn
            }

Upvotes: 1

Related Questions