8
using(DataContext db = new DataContext ())
{
    var result = db.SomeTable.ToList();
    return result;
}

Problem is after i have returned the result, the connection is closed and because its closed, it crashes when i am trying to access any of the child elements. That happens because with lazy loading set to True ( default ) it never loads the child relations before they are used and i start using them AFTER the connection is closed. So how is the best way to solve this?

I have tried to turn off the lazy loading but then it didnt load any of the child relation tables.

Alex Angas
  • 59,219
  • 41
  • 137
  • 210
syncis
  • 1,395
  • 4
  • 25
  • 43

2 Answers2

14

You can always explicitly load your child collections:

var result = db.SomeTable.Include("SomeChildCollectionName")
                         .Include("AnotherChildCollectionName")
                         .ToList();
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • Ok but what if i want to load ALL child elements without having to explicitly writing include("ElementName") ? There is a lot of child elements , thats why – syncis Jan 10 '11 at 14:49
  • @user554978 - That isn't supported. You have to explicitly load all the children up front using Include or keep the connection open and allow Lazy Loading to do its thing. – Justin Niessner Jan 10 '11 at 14:50
3

You can use the .include() method.

var result = db.SomeTable.Include("ChildEntitySet").ToList();

You can also add a result.ChildEntitySet.Load() call before returning. This is less efficient as it will result in two trips to the server. Using the .Include() method will generate a SQL Statement with a JOIN allowing only one trip to the server.

DCNYAM
  • 11,966
  • 8
  • 53
  • 70
  • 1
    Ok but what if i want to load ALL child elements without having to explicitly writing include("ElementName") ? There is a lot of child elements , thats why – syncis Jan 10 '11 at 14:49