Entity Framework Pitfalls: Null Navigation Properties

What if, after you load an entity, you have a reference property for another entity that is null yet you are sure that it points to a valid record? This will likely be because of one of two things:

  • Lazy loading is globally disabled (the LazyLoadingEnabled or ProxyCreationEnabled are set to false);
  • The containing entity does not qualify for lazy loading (it is sealed or the reference property is not virtual).

Anyway, you can always tell by code if the property is still unloaded and force it to load:

   1: if (ctx.Entry(entity).Reference(x => x.MyReference).IsLoaded == false)
   2: {
   3:   ctx.Entry(entity).Reference(x => x.MyReference).Load();
   4: }

                             

2 Comments

  • It was really helpfull for me!!

    Thank you!!

  • Thanks for sharing this. I hadn't hit the problem before and it had me stumped.

    In my case, I use: context.Configuration.ProxyCreationEnabled = false;

    I don't know if this is true for yours second scenario, but for me adding

    .Include("MyReference")

    to the original statement also resolved my problem without having to iterate through the results.

Add a Comment

As it will appear on the website

Not displayed

Your website