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.

2 Answers 2

14

You can always explicitly load your child collections:

var result = db.SomeTable.Include("SomeChildCollectionName")
                         .Include("AnotherChildCollectionName")
                         .ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

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
@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.
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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.