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 Element
s with related Unit
s.
Like this:
Context.Elements.Include(o => o.Unit);
Our expectation was that only Element
s would have a Unit
. However the Unit
s do also have Element
s
{
"Id": 1,
"Unit": {
"Id": 1,
"Elements":[...]
}
}
How do we exclude the Element
s from Unit.Elements
?
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
There is currently no solution for this.
As pointed out here there is a workaround available:
Context.Elements.Include(o => o.Unit).Select(o => new Element()
{
Id = o.Id,
Unit = o.Unit
});