Home >Backend Development >C++ >Why Are EF Core Navigation Properties Null Until Direct Access to Related Entities?

Why Are EF Core Navigation Properties Null Until Direct Access to Related Entities?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-24 22:16:10613browse

Why Are EF Core Navigation Properties Null Until Direct Access to Related Entities?

EF core delay loading navigation attributes

Question:

In the Entity Framework Core (EF Core) model, the navigation attribute returned to the empty value before directly accessing the relevant entities.

Model:

Query question:

<code class="language-csharp">public class Mutant
{
    ...
    public virtual OriginalCode OriginalCode { get; set; }
}

public class OriginalCode
{
    ...
    public virtual ICollection<Mutant> Mutants { get; set; }
}</code>
When retrieving the mutant, the OriginalCode navigation attribute is empty:

Dynamic filling of the relationship:

But when querying related OriginalCode entities:
<code class="language-csharp">var mutants = db.Mutants.ToList();
mutants.ForEach(m => Console.WriteLine(m.OriginalCode == null));
// 输出:所有突变体均为True</code>

ORIGINALCODE navigation attributes of mutants will automatically fill in:

Explanation:

<code class="language-csharp">var originalCodes = db.OriginalCodes.ToList();</code>

EF Core's pre -loading mechanism will automatically fill the navigation attributes of the relevant entities that have been loaded to the context. In the second case, when searching OriginalCodes, the corresponding mutant will also be loaded into the context, so their navigation attributes will be filled.

<code class="language-csharp">mutants.ForEach(m => Console.WriteLine(m.OriginalCode == null));
// 输出:所有突变体均为False</code>
Solution:

To control this behavior, the explicit loading method should be used, such as pre -load:

or, to prevent automatic filling, use a new DBContext instance or no tracking query.

Update:

In EF Core V2.1, it now supports delay loading. To enable it, mark the navigation attributes as Virtual, install microSoft.entityFrameworkCore.proxies, and call UseelazyLoadingProxies.

The above is the detailed content of Why Are EF Core Navigation Properties Null Until Direct Access to Related Entities?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn