将Linq中的子表上的where条件应用于SQL
本文关键字:条件 where 应用于 SQL Linq | 更新日期: 2023-09-27 18:22:03
我有一个表TableA和子表TableB。我想获取所有的父表记录,而是选择满足条件的子记录。我正在使用include获取子记录。
除了使用select new之外,还有其他直接的方法吗?
LINQ to SQL有一个LoadOptions,您可以在上下文中设置它来执行一些功能强大的操作。大多数人都指向.LoadWith,它急切地加载子记录。还有一个AssociateWith,它指定要应用于懒惰子获取的过滤。它们都可以采用lambda表达式进行子级筛选。这里有一个例子:
var lo = new DataLoadOptions();
lo.AssociateWith<Customers>
(c => c.Orders.Where(o => !o.ShippedDate.HasValue));
this.LoadOptions=lo;
var query = from c in Customers
select c.Orders;
注意,这仅适用于LINQ to SQL。EF目前不支持这种行为。
using (var context = new DbEntities()) {
foreach (var p in context.Parents) {
var childQuery = from c in p.Children
where c.whatever == something
select c;
// Do something with the items in childQuery, like add them to a List<Child>,
// or maybe a Dictionary<Parent,List<Child>>
}
}