我想获得一组客户,其中包括几个属性,其中包括地址,但仅限于尚未删除的地址(SuppressionDate == null
)
IQueryable<Customer> customers =
context.Persons.OfType<Customer>()
.Include(customer => customer.Addresses)
.Include(customer => customer.Bills)
.Include(customer => customer.Code)
.Include(customer => customer.Tutors);
我尝试了几种使用where子句的方法来过滤地址:
...
.Include(customer => customer.Addresses.Where(a => a.SuppressionDate == null))
.Include(customer => customer.Bills)
...
这是我的第一次尝试,但它引发了以下异常:
System.ArgumentException:Include路径表达式必须引用a 在类型上定义的导航属性。使用虚线路径 引用导航属性和集合的Select运算符 导航属性。参数名称:路径
我也尝试在Include()
末尾和查询结尾处使用相同的where子句,但似乎都不起作用。
我目前正在使用一种解决方法,该方法遍历客户集合并删除已删除的地址:
foreach(Customer c in customers){
customer.Addresses = customer.Addresses.Where(a => a.SuppressionDate == null).ToList();
}
作为对象/实体的linq相当新,我想知道是否有内置的方法来实现这一点。
答案 0 :(得分:0)
如果您获得单个客户,您可以使用这样的显式加载:
var customer = context.Persons
.OfType<Customer>()
.Include(customer => customer.Bills)
.Include(customer => customer.Code)
.Include(customer => customer.Tutors)
.FirstOrDefault(); //or whatever
context.Entry(customer).Collections(x => x.Addresses).Query().Where(x => x.SuppressionDate == null).Load();
这是一个很好的查询和对数据库的两个简单调用。但在这种情况下,您将获得一个客户列表(或集合或其他),并且没有捷径。你的“解决方法”可能会引起很多与数据库的讨论。
所以你可能只需要一步一步:
//1. query db to get customers
var customers = context.Persons
.OfType<Customer>()
.Include(customer => customer.Bills)
.Include(customer => customer.Code)
.Include(customer => customer.Tutors)
.ToList();
//2. make an array of all customerIds (no db interation here)
var customerIds = customers.Select(x => x.CustomerId).ToArray();
//3. query db to get addresses for customers above
var addresses = context.Addresses.Where(x => customerIds.Contains(x.CustomerId).ToList();
//4. assign addresses to customers (again, no db chatter)
foreach (var customer in customers)
{
customer.Addresses = addresses
.Where(x => x.CustomerId == customer.CustomerId && x.SuppressionDate == null)
.ToList();
}
还不错 - 仍只是对数据库的两次查询。