This is a migrated thread and some comments may be shown as answers.

How to query multiple tables in linq

1 Answer 92 Views
LINQ (LINQ specific questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
nanak
Top achievements
Rank 1
nanak asked on 10 Jul 2010, 05:50 PM
i all.

i have three tables named forum , topics & posts  i want some columns from forum table and according to the forumid i want total topics available & post available

here is the query i am using but don't know exactly how it will work.

    you may have seen on many forum websites they show forum name total topics in it and total posts in it. i want the exact same.

    public IQueryable GetAllForums_TopicsCount_PostCount()
        {
            eld = new ELearnDataContext();
            var query = from n in eld.Forums
                        join m in eld.ForumTopics
                        on n.ForumID equals m.ForumID
                        select new { n.IconFile, n.Title, n.Description, n.DateCreated
                       
                     
                       
                        };
            return query;
        }

1 Answer, 1 is accepted

Sort by
0
Serge
Telerik team
answered on 14 Jul 2010, 05:45 PM
Hello Nanak,

It seems that you have taken the wrong approach here. I will assume that you have collection members on each class, by that I mean the forum class has a collection property of type topics and the topic class has a collection property of type post. If you do not have such properties in your model I suggest reading "Defining a Domain Model" section of the OpenAccess help installed on your machine as well as having a look at the LINQ 101 Samples that are also installed on your machine (you can also find them online here).

However if you do have such a model your code for accessing this should look a little like this : 

using (ElearnDataContext context = new ElearnDataContext())
{
    foreach (Forum forum in context.Forums)
    {
        Console.WriteLine(forum.Topics.Count);
        Console.WriteLine(forum.Topics.Sum(x => x.Posts.Count));
    }
}

I hope this helps. If  you need further information please do not hesitate to contact us back.

Best wishes,
Serge
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
Tags
LINQ (LINQ specific questions)
Asked by
nanak
Top achievements
Rank 1
Answers by
Serge
Telerik team
Share this question
or