开发者

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

开发者 https://www.devze.com 2023-02-18 09:47 出处:网络
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 f

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?


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();


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.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消