Load navigation property from inherited class

蓝咒 提交于 2019-12-19 08:27:57

问题


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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/18186803/load-navigation-property-from-inherited-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!