Question

public class Unit
{
   Public int Id { get; set; }
   Public virtual ICollection<Element> Elements { get; set; }
}

public class Element
{
   public int Id { get; set; }
   public virtual Unit Unit { get; set; } 
}

We use a API call to get all Elements with related Units. Like this:

Context.Elements.Include(o => o.Unit);

Our expectation was that only Elements would have a Unit. However the Units do also have Elements

{
  "Id": 1,
  "Unit": {
     "Id": 1,
     "Elements":[...]
  }
}

How do we exclude the Elements from Unit.Elements?

1
1
8/9/2018 8:06:38 AM

Popular Answer

EF Core populate entity's navigation properties if related entities already loaded in the memory.

Context.Element.Include(e => e.Unit) 

Line above will load all Element entities in the memory, so it will populate Unit.Elements as well.

Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.

EF Core 2.1 now supports lazy loading which probably could answer your question, but, as I mentioned above, in your case all Elements already loaded in the memory.

Loading Related Data - Lazing Loading

1
8/9/2018 12:25:08 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