ArielBH
ArielBH

Reputation: 2001

Simplest way to do Lazy Loading with LINQ2SQL

I have a read-only database, so I am turning off ObjectTracking (thus implicitly turning off DeferredLoading).

I wish to do lazy loading and not use LoadWith<>.

What is the simplest way to explicitly tell Linq to go and lazy fetch a relation just before I need the data itself.

For example: a simple dbml alt text

If I have the following code:

  TestDbDataContext context = new TestDbDataContext(Settings.Default.TestersConnectionString);
  context.ObjectTrackingEnabled = false;

  var result = context.Employees.ToList();
  foreach (var employee in result)
  {
    // HERE Should load gift list
    foreach (var gift in employee.Gifts)
    {
      Console.WriteLine(gift.Name);
    }
  }

I know I can write a full query again, but I hope we can find together a better way.

Upvotes: 2

Views: 929

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062745

You are fighting the system... 2 thoughts:

  • if you know you need the other data (nested foreach), why wouldn't you want to use LoadWith? That is pretty-much the text-book use case
  • since you (from post) know that object tracking is required for lazy loading, why not just enable object tracking; data-contexts should usually be considered "units of work" (i.e. short-lived), so this isn't likely to hurt much in reality.

See the official replies here for why these two options (object tracking and deferred loading) are linked.

Upvotes: 2

Related Questions