Load navigation property from inherited class

I want to get all contact objects (including Person -> Employees)

Contact |<- Person | |-> Employer | |<- Organization | |-> Employees 

The user and organization inherit from Contact.

When I use FirstOrDefault, my employees and my employer's facility were not loaded.

 public Contact GetContactById(int id) { var contact = GetContacts().FirstOrDefault(c => c.Id == id); return contact; } private IQueryable<Contact> GetContacts() { var contacts = _contextProvider.Context.Contacts .Include("Addresses"); return contacts; } 

What is my current workaround:

 public Contact GetContactById(int id) { var contact = GetContacts().FirstOrDefault(c => c.Id == id); if (contact is Organization) { var organization = contact as Organization; _contextProvider.Context.Entry(organization).Collection(o => o.Employees).Load(); } else if (contact is Person) { var person = contact as Person; _contextProvider.Context.Entry(person).Reference(o => o.Employer).Load(); } return contact; } 

Is there a better way to solve this problem?

+4
source share
1 answer

I cannot verify this, but a possible push in the right direction may be

 private IQueryable<Contact> GetContacts() { var people = _contextProvider.Context.Contacts .OfType<Person>() .Include("Employer"); var organizations = _contextProvider.Context.Contacts .OfType<Organization>() .Include("Employees"); return people.Concat<Contact>(organizations); } 
+4
source

Source: https://habr.com/ru/post/1496570/


All Articles