Unique Behavior when querying using primary key column in linq to SQL

I was working on a query earlier in the day when I came across this behavior when searching for a record using primary key in linq to SQL. Basically when you query for an object the first time using linq to SQL, datacontext caches the object in its tracking service. Therefore next time around when you query for the object again, it retrieves the modified object from the cache. It is worth noting that if you are querying based anything that is not a primary key column than linq to SQL would make a database call the second time around as well. After completing the database call, it will than check with the data tracking service to see if that object is available in its cache. If it is available, it will return the object from its tracking service. However when you are querying based on primary key column, it does not bother making the database call, it simple ask the object from the tracking service first and if it is found it simply returns it. If the tracking service does not have the object than linq to SQL goes and makes a database.

Here is an example that confirms this behavior.

image

image

In the first example I am retrieving the customer by primary key column and than changing the contact name value. The next time around when I look up the same customer using the customerid, the primary key column, I get the modified object. Notice in the output window when I am searching based on primary key column, the SQL is logged only once. And that is because linq to SQL executes the query only once.

In the second option, when I am querying using contact name second time, I also get a modified object,however the query gets executed both the times as shown in the output window.

No Comments