Frage

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

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

Person and Organization inherits from Contact.

When i use FirstOrDefault my employees and my employer entity 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;
}

That's 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?

War es hilfreich?

Lösung

I can't test this but a possible nudge in the right direction could 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);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top