Avoid attaching parent entity on child entities using EF Core

c# entity-framework-core

Question

I got this hierarchical table setup Company has a reference to Postal and Postal has a reference to Area. I'm using EF Core.

class Company { CompanyId, .., PostalId, Postal }
class Postal { PostalId, .., Company }
class Area { AreaId, .., Postal }

My problem is that the Company entity is added to every Postal entity like a circual reference.

Company
 -Postal
  -Company
  | -Postal
  |  -Company
  |  | -Postal
  |  |  -Company
  |  |  -Area
  |  -Area
  -Area

Maybe this behavior is intended but it generates a lot of data overhead. Is there a way to prevent child entity to reference parent entities.

When querying for entities I use code like this:

db.Companies.Include(p => p.Postal).ThenInclude(a => a.Area)
1
0
2/15/2020 9:00:54 PM

Accepted Answer

I came to the conclusion that it is not possible to avoid these circular entities attachment. It is just how Entity Framework works at the moment. Because of the output data overhead generated by this issue, I've choosen the .Select(new ) solution. Here I can decide what properties to bubble up and avoid those not to. This solution also has a performance improvement. I bit more work, but the result is good.

0
2/23/2020 8:56:46 AM


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