我有以下实体:
申请人来自Person
。 Applicant
有很多PhoneNumber
(最多三个)。每个PhoneNumber
只有1个PhoneType
。
public class Applicant : Person
{
public virtual ICollection<PhoneNumber> PhoneNumbers { get; set; }
}
public class PhoneNumber
{
public int PersonId { get; set; }
[Required]
[MaxLength(17)]
public string Number { get; set; }
public int PhoneTypeId { get; set; }
public virtual PhoneType PhoneType { get; set; }
}
public class PhoneType
{
[Required]
[MaxLength(24)]
public string Name { get; set; }
public virtual ICollection<PhoneNumber> PhoneNumbers { get; set; }
}
在我看来,我正在使用的两个查询可以合并,并且可以取消foreach循环,但是我在第一个查询中已经有大量的联接,而且我不确定如何合并它们。问题是一个两部分的问题:
PhoneNumber
/ PhoneType
查询。 目标是返回带有Applicant
列表的PhoneNumber
,返回每个带有PhoneNumber
的PhoneType
。为了清楚起见,类型为:家庭,办公室和手机。
/*------------------------------------------*/
/* Obtain the Applicant */
/*------------------------------------------*/
IQueryable<Applicant> applicantQuery =
DbContext.Applicants.Where(a => a.CreatedBy == userId)
.Include(applicant => applicant.Address)
.Include(applicant => applicant.Address.StateProvince)
.Include(applicant => applicant.PhoneNumbers)
.Include(applicant => applicant.HomeChurch)
.Include(applicant => applicant.HomeChurch.Address)
.Include(applicant => applicant.HomeChurch.Address.StateProvince)
.Include(applicant => applicant.TripApplication);
Applicant applicant = applicantQuery.FirstOrDefault<Applicant>();
if (applicant != null && applicant.PhoneNumbers != null)
{
IQueryable<PhoneType> phoneTypeQuery = DbContext.Set<PhoneType>();
List<PhoneType> phoneTypes = phoneTypeQuery.ToList<PhoneType>();
foreach (PhoneNumber ph in applicant.PhoneNumbers)
{
ph.PhoneType = (phoneTypes.Where(pt => pt.Id == ph.PhoneTypeId)).First();
}
}
预先感谢您提供的任何帮助。
EF Core通过将ThenInclude()]和ThenInclude()组合在一起来支持加载多个级别,更多信息here
将电话和电话类型一起装扮,您的查询应如下所示(为了清楚起见,我删除了其余的关系):
var applicant = DbContext.Applicants.Where(a => a.CreatedBy == userId)
.Include(applicant => applicant.PhoneNumbers)
.ThenInclude(phone => phone.PhoneType)
.FirstOrDefault();