从继承的类加载导航属性 [英] Load navigation property from inherited class
本文介绍了从继承的类加载导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取所有联系人实体(包括人->员工)
I want to get all contact entities (including Person -> Employees)
Contact
|<- Person
| |-> Employer
|
|<- Organization
| |-> Employees
人员和组织从Contact继承。
Person and Organization inherits from Contact.
当我使用FirstOrDefault时,未加载我的员工和雇主实体。
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?
推荐答案
我无法对此进行测试,但可能会向正确的方向轻推
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);
}
这篇关于从继承的类加载导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文