EF Core lazy loading proxies return null randomly instead of entities

.net asp.net-core-3.1 c# entity-framework entity-framework-core

Question

I have a .Net Core 3.1 application with an SQL database. I use lazy-loading proxies to automatically retrieve data from related tables. Basically, I have a table, which references some other entities via 1-to-many or 1-to-1 relation. Thing is, most of the cases, every relation is OK, every entity is loaded and I can read it's properties (name field, for example).

But, in very specific cases, those entities won't load, although relation Id is there. It looks like this:

Model is like this:

public partial class Delegation
{
    public Guid Id { get; set; }
    public int UserFrom { get; set; }
    public int UserTo { get; set; }

    public virtual User UserFromNavigation { get; set; }
    public virtual User UserToNavigation { get; set; }
}

Initialization inside database context:

public virtual DbSet<Delegation> Delegations { get; set; }
...
modelBuilder.Entity<Delegation>(entity =>
{
    entity.Property(e => e.Id).ValueGeneratedNever();

    entity.HasOne(d => d.UserFromNavigation)
        .WithMany(p => p.DelegationsUserFromNavigation)
        .HasForeignKey(d => d.UserFrom)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("FK_Delegations_Users_From");

     entity.HasOne(d => d.UserToNavigation)
        .WithMany(p => p.DelegationsUserToNavigation)
        .HasForeignKey(d => d.UserTo)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("FK_Delegations_Users_To");
});

This specific example is only one of the many, there are also not loading virtual ICollections of other entities in other models.

Here, on debug screenshot, UserTo is OK, but UserFrom is NULL.

UserTo is OK, but UserFrom is NULL

Manually searching for the entity by Id and retrieving it's properties is working, but it makes code much dirtier.

Is there any way to force EF to load those missing entities or am I doing a mistake here? This behavior looks really random.

1
0
2/28/2020 2:17:24 PM

Popular Answer

You need to include UserToNavigation in your query as:

var delegation = rmsContext.Delegations.Include(x => x.UserToNavigation).Find(id);

for accessing db data, try to use async/await. Your query will become:

 var delegation = await rmsContext.Delegations.Include(x => x.UserToNavigation).FindAsync(id);
1
2/28/2020 2:23:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow