Search
Close this search box.

LINQ to SQL DataLoadOptions

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:

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);
           
        }
        
This article is part of the GWB Archives. Original Author: Kashif Khan

Related Posts