如何在父表和子表上设置条件

时间:2012-12-11 20:07:38

标签: linq linq-to-sql linq-to-entities

在下面的查询中,我想按其ID选择人,我只想包含活动地址。我该如何编写该查询?我不确定我写的那个是正确的

请注意,GetQuery()会返回IQueryable

var person = repositoryProvider.Repository.GetQuery<Person>()
    .Where(a => a.PersonID == 1234 && a.Addresses.Any(x=>x.IsActive))
    .Include(a => a.Addresses)
    .Include(a => a.Employer)                   
    .SingleOrDefault();

1 个答案:

答案 0 :(得分:0)

从我的阅读中,只有在至少有一个活动地址的情况下,您的查询才会获得1234人。但是,它将包括与Person 1234相关的所有地址。例如,如果人1234有一个活动地址和五个非活动地址,您将获得Person 1234的详细信息及其六个总地址,而不仅仅是活动地址。

出于您的目的,我认为子查询会这样做。

var person = repositoryProvider.Repository.GetQuery<Person>()
             .Where (a => a.PersonID ==1234)
             .Include(a => a.Address)
             .Include(a => a.Employer)
             .Select (p => new Person { Id = p.Id,  // <-- set the person's properties that you need using the person details that you have extracted.
                      FirstName = p.FirstName,
                      Employer = p.Employer.ToList()
                      Addresses = p.Addresses.Where(a => a.IsActive == true) // <-- transform the resulting entity such that it will only return active addresses
                      }).FirstOrDefault();

另一种可能更容易阅读的方法是将其分解为两部分。第一部分将提取人员详细信息:

var person = repositoryProvider.Repository.GetQuery<Person>()
             .Where (a => a.PersonID ==1234)
             .Include(a => a.Addresses)
             .Include(a => a.Employer)
             .Select (p => p);

然后第二部分将人员的地址限制为仅活动地址:

person.Addresses = person.Addresses.Where (a => a.IsActive == true).ToList();