2

I'm using ASP.NET MVC 4.5 with Entity Framework and everything I'm reading says my database context should be enclosed in a using statement to prevent memory leaks. However, when I pass my model to my view I lose the ability to join to other tables.

So if I have a model that has:

public class people
{
   public int id { get; set; }
   public sting name { get; set; }
   public virtual stuff things { get; set; }
}
public class stuff
{
   public int id { get; set; }
   public string name { get; set; }
   public int thingType { get; set; }
}

But if in my view I want to to loop add grab all of a persons's stuff I can't if I created my context in a using statement. What's the correct way to handle this?

2 Answers 2

3

You can retrieve the children while the context is still open. You can do it eagerly or lazily:

using (var context = new SomeContext()) {
    // This will do a JOIN on the SQL query,
    // which will bring everything in at once.
    var thePerson = context.people.Include("things").Single(p => p.id == 4);
}

using (var context = new SomeContext()) {
    // This will fire two queries but will retrieve
    // the same data as the previous example
    var thePerson = context.people.Single(p => p.id == 4);
    var theStuff = thePerson.things.ToList();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic. This is exactly what I was missing. Thanks for the help!
0

You should call ToList() on the child collections when setting the ViewModel inside the using block to fetch the child relations before disposing the context.

3 Comments

I don't think ToList() will fetch the children automatically - wouldn't you have to explicitly ask for them either eagerly with an .Include(), or lazily by calling the property while the context is still alive? I could be wrong with code first, but with database-first, you only get what you ask for.
I also am confident that ToList() will not fetch the child relations alone. They need to be explicitly retrieved before the context is disposed.
@Steve: I meant on the child collection. Clarified.

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.