0

I'm working on an enterprise application that leverages the repository pattern on top of EF 4.1 with eager loading to POCO entities. Typically, a call will look like this:

public IEnumerable<SomeEntity> List(DateTime date)
{
   using (var context = ContextFactory.CreateContext()) // Returns a DbContext
   {
      return CreateQuery<SomeEntity>(context)
         .Include("PATH1")
         .Include("PATH2")
         .Where(...)                  
         .AsNoTracking()
         .ToList();
   }
}

At some point, the business layer translates these entities into DTOs that are then transmitted via WCF to a web application.

As eager loading is rather expensive, I'm trying to keep .Include's to a minimum, so sometimes related properties are (eagerly) loaded and sometimes they're not. However, the business layer has no idea when related properties are present in the entity, so I get an ObjectContextDisposedException, the reason for which is perfectly clear to me and I don't intend to change the basic strategy (i.e. dispose the context right after eager loading the entities).

However, I need to check whether a particular related property is loaded or not, checking if the related object is null doesn't work (ObjectContextDisposedException), nor is there any kind of IsLoaded() method I could use.

Am I stuck with a try/catch block here or are there any other options?

Thorsten Westheider
  • 10,572
  • 14
  • 55
  • 97

1 Answers1

2

Turn off lazy loading and check for null will work. Your current solution cannot use lazy loading because you dispose context immediately after running the query:

context.Configuration.LazyLoadingEnabled = false;
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670