EF Core returns null relationships before direct access

I have several models like the ones below:

public class Mutant
{
    public long Id { get; set; }
    ...

    // Relations
    public long OriginalCodeId { get; set; }
    public virtual OriginalCode OriginalCode { get; set; }
    public int DifficultyLevelId { get; set; }
    public virtual DifficultyLevel DifficultyLevel { get; set; }
}

and

public class OriginalCode
{
    public long Id { get; set; }
    ...

    // Relations
    public virtual List<Mutant> Mutants { get; set; }
    public virtual List<OriginalCodeInputParameter> OriginalCodeInputParameters { get; set; }
}

and in OnModelCreating DBContexti made such a relationship:

        modelBuilder.Entity<Mutant>()
            .HasOne(m => m.OriginalCode)
            .WithMany(oc => oc.Mutants)
            .HasForeignKey(m => m.OriginalCodeId)
            .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);

        modelBuilder.Entity<Mutant>()
            .HasOne(m => m.DifficultyLevel)
            .WithMany(dl => dl.Mutants)
            .HasForeignKey(m => m.DifficultyLevelId)
            .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);

Now when I request Mutants, OriginalCode is null:

Null OriginalCode

but as soon as I request OriginalCodeas shown below:

OriginalCodes

then the field of OriginalCodemutants will not be zero:

Completed object

What is the reason and how can I fix this?

+17
source share
2 answers

The reason is explained in the “ Download Related Datasection of the EF Core documentation.

, EF Core , null , . Eager :


Entity Framework Core , . , , , .

, .

, , .

"" , , :

var mutants = db.Mutants.Include(m => m.OriginalCode).ToList();

" " . , DbContext , .

: 2.1, EF Core Lazy Loading. , virtual, Microsoft.EntityFrameworkCore.Proxies UseLazyLoadingProxies Lazy- - - EF Core .

+33

Source: https://habr.com/ru/post/1670222/


All Articles