如何对此实体框架查询进行改进

问题描述 投票:0回答:1

我有以下实体:

  • 申请人:人
  • 电话号码
  • PhoneType

申请人来自PersonApplicant有很多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循环,但是我在第一个查询中已经有大量的联接,而且我不确定如何合并它们。问题是一个两部分的问题:

  1. 如何合并两个查询和
  2. 如果不合并查询,如何改进PhoneNumber / PhoneType查询。

目标是返回带有Applicant列表的PhoneNumber,返回每个带有PhoneNumberPhoneType。为了清楚起见,类型为:家庭,办公室和手机。

/*------------------------------------------*/
/* 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();
    }
}

预先感谢您提供的任何帮助。

sql-server linq linq-to-sql entity-framework-core
1个回答
0
投票

EF Core通过将ThenInclude()]和ThenInclude()组合在一起来支持加载多个级别,更多信息here

将电话和电话类型一起装扮,您的查询应如下所示(为了清楚起见,我删除了其余的关系):

var applicant = DbContext.Applicants.Where(a => a.CreatedBy == userId)
        .Include(applicant => applicant.PhoneNumbers)                                                
        .ThenInclude(phone => phone.PhoneType)
        .FirstOrDefault();
© www.soinside.com 2019 - 2024. All rights reserved.