我希望获得所有联系人实体(包括人员 - >员工)
Contact
|<- Person
| |-> Employer
|
|<- Organization
| |-> Employees
个人和组织继承自联系。
当我使用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;
}
有没有更好的方法来解决这个问题?
答案 0 :(得分: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);
}