LINQ to SQL and the DataContext cache and deferred execution RRS feed

  • Question

  • Hi,

    I have a problem understanding the LINQ to SQL cache in conjunction wirn deferred execution.
    I understand that the DataContext caches read entities by identifying them´using the primary key. If an entity is read again from the database, it is is ignored since it already is in the cache.

    My problem is, that deferred execution obviously may cause multiple fetches of the records from the database, even if ALL of them are thrown away by the DataContext if they already are in the cache. 

    The following program demonstrates what I mean:

    Code Snippet

    AdventureWorksLTDataContext dataContext = new AdventureWorksLTDataContext();
    dataContext.Log = Console.Out;

    var products = from product in dataContext.Products
       where product.ListPrice > 30000 select product;

    foreach (var product in products) // First fetch

    foreach (var product in products) // Second fetch

    It's not only that I think, that the data is fetched twice. The log of the DataContext outputs two SQL statments too.

    So: Am I right?  Does the DataContext fetch all data again, when deferred execution takes place (and throws most or all of the read entities away)?

    Wednesday, April 30, 2008 12:19 AM


  • In the scenario that you've outlined, the query is indeed sent to the server twice.


    (To avoid the second round-trip, use an operator like ToList() at the end of your query.)






    Wednesday, April 30, 2008 12:56 AM