none
Lazy Loading Properties vs Child properties RRS feed

  • Question

  • I have a scenario where I have a DataContext with related tables, let's say:  Customer & Order
    I've generated 1 DBML file for them.

    I can query all orders with DataContext.Orders
    I can also query 1 particular customer's orders with DataContext.Customer.Orders

    My question is:  Are these 2 queries' results maintained and treated independently?  IE If I retrieve orders from various customer transactions that by using DataContext.Customer.Orders property, and then later want to enumerate the global list of all orders in the system (DataContext.Orders), is it requerying those order records that I already queried from other customers or is it smart and using some of the already cached order records?
    Consider the opposite case also.... First enumerate all orders, then look at specific customer's orders through the child property. Is it reloading those orders?


    Sunday, July 19, 2009 5:46 PM

Answers

  • LINQ to SQL maintains an object cache with each DataContext instance, keyed to the primary key of each entity.

    This means that if you ask for a customer or order entity with a primary key of x, you'll always get back the same object - no matter what query you use.

    Running a fresh query will result in it re-querying the server, but it won't re-populate the details for any entities that it's already cached:

    var cust = db.Customers.Single (c => c.ID == 1);      // c is cached

    foreach (var c in db.Customers)
    {
      Console.WriteLine (c.ID + " " + c.Name);           // Hits the database, but doesn't repopulate cust
      if (c.ID == 1) Console.WriteLine (c == cust);     // True
    }

    This same rules apply for entities retrieved through EntitySet properties (such as customer.Orders, in your example) except that the EntitySet collection itself is cached as well - so if you re-enumerate a customer's orders, it won't hit the database at all.

    Joe

    Write LINQ queries interactively - www.linqpad.net
    Monday, July 20, 2009 2:23 AM
    Answerer