Search code examples
c#sqldatabaselinqlinq-to-sql

LinqToSql query execution timing


I want to ask about the execution timing of a LinqToSql query.

From my understanding refer to this MSDN blog. It seems that a LinqToSql query will only execute when

  1. IQueryable's property is accessed
  2. IQueryable's function (which is not returning IQueryable/IEnumeration type) is called

However, I did an experiment like that:

var ents = from ent in dal.ents
           select ent;

string s1 = ents.first().Value1;   // I got 1 here
Console.ReadLine();    // When the system is waiting for my input. I change the same record manually in DB, I change Value2 of ent from 2 to 3 here. 
string s2 = ents.first().Value2    // I got 2 here.

Why am I still getting "2" for s2?

From my understanding, ents.first().Value2 should connect to the DB again and get the new Value2. Why am I still getting the old value?


Solution

  • Finally, I think I found the working principal behind. L2S is really working like

    LinqToSql query will only CONNECTION TO DB AND EXECUTE when

    1. IQueryable's property being accessed
    2. IQueryable's function (which is not returning IQueryable / IEnumeration type) being called

    But in additions, after L2S fetch data from DB for each record at the first time. It will cache the record by its PK.

    Eventually, on each further fetch. It will check if the record has been fetched before.

    1. yes, It will use the cached version of the record instead of the DB version.
    2. If no, It will use the DB version.

    P.S. The lifetime of the cached records will last until the DBContext being released.