简体   繁体   中英

Avoid attaching parent entity on child entities using EF Core

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM