如何将 Where 子句应用于 LINQ 表达式中深入几层的实体?



我正在开发一个LINQ表达式,它将把相关的表拉入到我们现有的Person表中。我编写的查询确实有效,但运行起来需要很长时间,而且返回的数据比我需要的要多。这是我现在的LINQ表达式:

using (var ctx = new AppEntities())
{
People = ctx.People.Where(p => p.Inactive == false)
.Include(p => p.Agency)
.Include(p => p.PersonnelCertifications.Select(pc => pc.CertificationType))
.OrderBy(p => p.LastName)
.ThenBy(p => p.FirstName)
.ToList();
}

我们正在使用.NET 4.5.2和EF 6.4。Person表与PersonnelCertification表具有相关性。这与CertificateType表有关系。理想情况下,我需要添加一个过滤器,以便只有CertificateType.CertType==";操作员";。我尝试在IncludeofPersonnelCertificates之后添加Where子句,但没有成功。第二个Where子句仍然只适用于Person表。有办法做我想做的事吗?如果是,如何做到这一点?

为了简洁起见,以下是删除了无关字段的表定义:

public partial class Person
{
public Person()
{
PersonnelCertifications = new HashSet<PersonnelCertification>();
}
public long ID { get; set; }
public virtual ICollection<PersonnelCertification> PersonnelCertifications { get; set; }
}
public partial class PersonnelCertification
{
public long ID { get; set; }
public long CertificationTypeID { get; set; }
public long PersonID { get; set; }
public virtual CertificationType CertificationType { get; set; }
public virtual Person Person { get; set; }
}
public partial class CertificationType
{
public CertificationType()
{
PersonnelCertifications = new HashSet<PersonnelCertification>();
}
public long ID { get; set; }
[Required]
[StringLength(30)]
public string CertType { get; set; }
public virtual ICollection<PersonnelCertification> PersonnelCertifications { get; set; }
}

.Where(p => p.PersonnelCertifications.Any(pc => pc.CertificationType == "Operator"))应该会为您提供所需人员。

最新更新