Home > Software design >  EF6 - Lazy loading related entity always null
EF6 - Lazy loading related entity always null

Time:12-29

For some reason, the lazy loading of a related entity always turns out NULL. I think I followed all the needed rules to apply for the proxy generation, however I don't seem to be able to resolve this issue.

I have an object tblOrder_Procedure that has a tblRoom and a tblProcedure. For some reason tblProcedure always loads automatically, but tblRoom doesn't. The FK however is there, but the related entity is just not loaded.

All classes have public parameterless constructors.

These are the field definitions:

public int? Procedure_UID { get; set; }
public int? Room_UID { get; set; }
public virtual tblRoom tblRoom { get; set; }
public virtual tblProcedure tblProcedure { get; set; }

I don't use annotations, but use the OnModelCreating method of the context with fluent API. The FK's are done like this:

modelBuilder.Entity<tblRoom>()
    .HasMany(e => e.tblOrder_Procedure)
    .WithOptional(e => e.tblRoom)
    .HasForeignKey(e => e.Room_UID);
modelBuilder.Entity<tblProcedure>()
    .HasMany(e => e.tblOrder_Procedure)
    .WithOptional(e => e.tblProcedure)
    .HasForeignKey(e => e.Procedure_UID);

ProxyCreationEnabled and LazyLoadingEnabled are both true by default for the context.

What am I missing?

CodePudding user response:

I'll write down the two most likely possibilities.

-Maybe you are using the .AsNoTracking() extension somewhere explicitly or hidden by another helper that you've written.

-You can try to add optionsBuilder.UseLazyLoadingProxies(); to Context.OnConfiguring(DbContextOptionsBuilder optionsBuilder).

CodePudding user response:

afaik, if you are using virtual keyword, you should use "include" method.

modelBuilder.Entity<tblRoom>()
    .Include(f=>f.tbl_room)
    .HasMany(e => e.tblOrder_Procedure)
    .WithOptional(e => e.tblRoom),
    .HasForeignKey(e => e.Room_UID);
  • Related