Skip to content

Instantly share code, notes, and snippets.

@mvalipour
Created November 3, 2016 14:06
Show Gist options
  • Select an option

  • Save mvalipour/af87643cf167cc0cef51eb62d8f51221 to your computer and use it in GitHub Desktop.

Select an option

Save mvalipour/af87643cf167cc0cef51eb62d8f51221 to your computer and use it in GitHub Desktop.
A note on using EF utilizing lazy loading

When using EF (or any other ORM utilizing lazy loading) DO NOT pass your entity objects around different layered of your application.

Just turn them into a purpose-built DTO ASAP.

Gotcha: otherwise you will get a ObjectContext disposed error whenever the code retrieving your eneity changes the way it handles the retrieval (context dispose).

in other words: this code:

using(var context = new MyContext())
{
  var item = context.FindById(123);
  DoSomething(item);
}

may one day become:

var item;
using(var context = new MyContext())
{
  item = context.FindById(123);
}
DoSomething(item);

If you pass on the item like above, any lazily loaded prop of item will fail due to context being disposed.

this is what it should look like:

var itemDto;
using(var context = new MyContext())
{
  var item = context.FindById(123);
  itemDto = ConvertToDto(item);
}
DoSomething(itemDto);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment