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>
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>
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!