Morten Mertner
Morten Mertner

Reputation: 9474

How do I map entities with lazy-loaded properties (without causing them to load)?

I'm using EF 4.1 and code-first in an MVC project, and AutoMapper to map entities to view models.

Prior to using code-first I was able to exclude navigation properties in order to prevent anything from being loaded that wasn't already. I'm using .Include() in my queries to include the references that I need in order to avoid additional database round-trips.

However, with code-first my entity only exposes an entity property (or ICollection if there are more than one). How can I know whether it has been loaded without triggering the load?

Assuming this can be done, is there a way to make this the default behavior for AutoMapper, so that I do not have to explicitly exclude members on every single entity?

Upvotes: 7

Views: 2829

Answers (3)

Goran Obradovic
Goran Obradovic

Reputation: 9051

EF Code First does lazy loading only for properties marked as virtual (it can override those and place DynamicProxy instead of it). If you don't make your property virtual, you will turn off lazy loading for that property.

Upvotes: 4

Slauma
Slauma

Reputation: 177133

You can check whether a reference or collection navigation property of an entity has been loaded by:

bool isLoaded1 = dbContext.Entry(entity).Reference(e => e.MyReferenceProperty)
                     .IsLoaded();
bool isLoaded2 = dbContext.Entry(entity).Collection(e => e.MyCollectionProperty)
                     .IsLoaded();

Upvotes: 11

BrokenGlass
BrokenGlass

Reputation: 160852

You should be able to explicitly load them by turning off lazy-loading:

using(var context = new FooBarEntities())
{
  context.ContextOptions.LazyLoadingEnabled = false;
  Foo foo = context.Foo.Where(x => x.Id == myId).Single();
  ...
  if(!foo.Bars.IsLoaded)
  {
      foo.Bars.Load();
  }
  //do something with foo.Bars here
}

Upvotes: 2

Related Questions