views:

89

answers:

1

Suppose I have an Entity Order with OrderDetails as child preperty.

I enable lazyloading like this:

  _context.ContextOptions.LazyLoadingEnabled = true;

I Can feed a view with a method like this:

Order.GetAll()

And navigate by the order details automatically without getting the wirerd "Object reference not set to an instance of an object" error??

A: 

If you have lazy loading, when you load up the objects you need to explicitly include the sub objects.

So Order.GetAll() will include

return context.Orders.Include("OrderDetails");

Another alternative is to load up the order details later, like so:

if (!order.OrderDetailsHeaders.IsLoaded)
{
    order.OrderDetailsHeaders.Load();
}
Mac
I think the above applies if lazy loading is set to false, not true... correct?
Scott
@Scott, no I don't think so. Lazy loading means that child elements are not loaded when an entity is loaded. You have to explicitly load child entities using .Include or .Load.
Mac
@Mac, you are correct that LazyLoadingEnabled=true; will not load children when an entity is loaded... but it will automatically load any entity the first time you try to access it with a navigation property without requiring you to explicitly load it yourself. Alternatively, you can use .Include to load children immediately, or set LazyLoadingEnabled=false; and call .Load before you need to access an entity. See this link: http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontextoptions.lazyloadingenabled.aspx
Scott
Sorry for the messy guys.....I Just forgot to put my business objects as virtual properties. Thanks for all.
Diego Correa