LINQ

Read-Only Data in LINQ

By default CRUD operation can be performed on the retrieved data from LINQ query. We can modify the data fetched through LINQ query.

IF we do not want to modify the data then we can increase the performance by making the data as READ ONLY.

clip_image002

 

If we set ObjectTrackingEnabled as false for DataContext then framework will not track the changes done on the DataContext.

Program.cs

using System;
using System.Linq;
using System.Data.Linq;
namespace ConsoleApplication5
  {
    class Program
        {
            static void Main(string[] args)
                {
                    DataClasses1DataContext context = new DataClasses1DataContext();
                    context.ObjectTrackingEnabled = false;
                    var result = from r in context.Persons orderby r.FirstName select r;                   
                    foreach (var r in result)
                    {
                        Console.WriteLine(r.FirstName + " " + r.LastName);
                    }                   
 
                    Console.ReadKey(true);                   
 
                }
        }
}
 

Output

clip_image004

There are two scenarios while ObjectTrackingEnabled as false can throw exception

 

1. If we execute the query and after that making the ObjectTrackingEnabled as false.

 

clip_image006

Then we will get below exception

clip_image007

2. If we try to perform submitchanges() operation because DataContext is on readonly.

About Dhananjay Kumar

Dhananjay Kumar is Developer, Blogger , Speaker, Learner , Mindcracker & Microsoft MVP.

Discussion

Trackbacks/Pingbacks

  1. Pingback: Monthly Report January 2010: Total Posts 19 « debug mode…… - December 4, 2011

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1,380 other followers

Tweets

Categories

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway. © Copyright 2012