Geeks With Blogs
AzamSharp Some day I will know everything. I hope that day never comes.

One of the good things about LINQ to SQL is that it gives the developer flexibility to choose the specified columns of a table from a database. Let's say I have table Forums and Posts and I need to get all the Forums and their Posts but I want to exclude the "Description" property of the Posts table. I want to exclude it because "Description" might be really long and loading the description will slow the fetching.

LINQ to SQL designer helps you to delay load a property as shown in the screen shot below:

linqtosqldelayloaded

Now, you can run the following query:

 static void Main(string[] args)
        {
            DiscussionBoardDataContext db = new DiscussionBoardDataContext();

            var query = from f in db.Forums
                        join p in db.Posts
                        on f.ForumID equals p.ForumID
                        select p;

            Console.WriteLine(query);
           
        }

And you will get the following query generated:

SELECT [t1].[PostID], [t1].[ForumID], [t1].[Title]
FROM [dbo].[Forums] AS [t0]
INNER JOIN [dbo].[Posts] AS [t1] ON [t0].[ForumID] = [t1].[ForumID]

As, you can see in the above query the "Description" column of the Posts table is not selected. If you do want to select the description column then you can tell LINQ to SQL using the DataLoadOptions feature.

 static void Main(string[] args)
        {
            DiscussionBoardDataContext db = new DiscussionBoardDataContext();

            DataLoadOptions options = new DataLoadOptions();
            options.LoadWith<Post>(p => p.Description);

            db.LoadOptions = options;

            var query = from f in db.Forums
                        join p in db.Posts
                        on f.ForumID equals p.ForumID
                        select p;

            Console.WriteLine(query);
           
        }

Posted on Saturday, March 29, 2008 9:24 AM | Back to top


Comments on this post: LINQ to SQL DataLoadOptions

# re: LINQ to SQL DataLoadOptions
Requesting Gravatar...
Here is a link that provide good explanation of working with LINQ to SQL DataLoadOptions and other best practices while using LINQ

http://www.a2zmenu.com/LINQ/LINQ%20to%20SQL%20DataLoadOptions.aspx
Left by ExpertsComment on Sep 05, 2010 9:34 AM

Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net | Join free