EF Core explicit ignore relation

2019-03-05 09:57发布

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?

2条回答
唯我独甜
2楼-- · 2019-03-05 10:16

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
});
查看更多
贼婆χ
3楼-- · 2019-03-05 10:29

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

查看更多
登录 后发表回答