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
IQueryable
's property is accessedIQueryable
's function (which is not returning IQueryable
/IEnumeration
type) is calledHowever, 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?
Finally, I think I found the working principal behind. L2S is really working like
LinqToSql query will only CONNECTION TO DB AND EXECUTE when
- IQueryable's property being accessed
- 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.
P.S. The lifetime of the cached records will last until the DBContext being released.