EF Core lazy loading proxies return null randomly instead of entities

被刻印的时光 ゝ 提交于 2020-06-26 16:23:26

问题


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.

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.

来源:https://stackoverflow.com/questions/60453551/ef-core-lazy-loading-proxies-return-null-randomly-instead-of-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!