4

我想获取所有联系实体(包括人员 -> 员工)

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

Person 和 Organization 继承自 Contact。

当我使用 FirstOrDefault 我的员工和我的雇主实体时没有加载。

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

这是我目前的解决方法:

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

有没有更好的方法来解决这个问题?

4

1 回答 1

4

我无法对此进行测试,但可能会朝着正确的方向轻推

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);
}
于 2013-08-12T12:54:23.040 回答