EF Core explicit ignore relation

2019-03-05 10:24发布

问题:

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:

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



回答2:

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
});