在Linq中将子表上的where条件应用于SQL

时间:2013-07-12 14:18:08

标签: c# linq linq-to-sql

我有一个表TableA和子表TableB。我想获取所有父表记录, 但选择满足条件的子记录。我使用include来获取子记录。

除了使用select new之外还有其他方法吗?

2 个答案:

答案 0 :(得分:2)

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目前不支持此行为。

答案 1 :(得分:0)

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>>
    }
}