简体   繁体   中英

EF6 - Lazy loading related entity always null

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?

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).

I figured out what the problem was. It had 2 origins:

  1. I was using an object that was newly created and inserted in the database to try to use lazy loading on. It turns out that you then need to use.Create() instead of 'new' for creating that object.

  2. Turns out I was using a too-long-lived databasecontext. Somewhere before having the problem, the tblProcedure object was already loaded into the context cache and thus the foreign key relation could be resolved. This made it look like it was lazy loaded, but it actually wasn't.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM