How to compare objects with lazy properties (without loading them)?

I use EF 4.1 and the first code in the MVC project and AutoMapper to map objects to view models.

Prior to using the code for the first time, I was able to exclude navigation properties to prevent things from loading that weren't loaded yet. I use .Include () in my queries to include the links I need to avoid extra visits to the database.

However, with the first code, at first my entity only provides the entity property (or ICollection, if there are more than one). How can I find out if it is loaded without starting the download?

Assuming this can be done, is there a way to do this by default for AutoMapper, so I don’t need to explicitly exclude members for each individual organization?

+6
c # entity-framework ef-code-first automapper
source share
3 answers

You can check if the link or collection binding property for the entity been loaded:

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

EF Code First, it does lazy loading only for properties marked as virtual (it can override them and place DynamicProxy in its place). If you do not make your property virtual, you will disable lazy loading for this property.

+4
source share

You can explicitly load them by disabling 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 } 
+2
source share

All Articles