如何:控制所检索的相关数据量 (LINQ to SQL)

更新:November 2007

使用 LoadWith 方法可指定应同时检索与主目标相关的哪些数据。例如,如果您了解将需要有关客户订单的信息,则可以使用 LoadWith 来确保在检索客户信息时会检索订单信息。这种方法的结果是只检索一次数据库即可获取这两组信息。

说明:

通过将叉积作为一个大型投影检索,可以检索与您的查询主目标相关的数据,例如在以客户为目标时检索订单。但这种方法往往存在弊端。例如,所得结果仅仅为投影,而不是可以由 LINQ to SQL 更改和持久化的实体。此外,您可能会检索到您并不需要的大量数据。

示例

在下面的示例中,在执行查询时会检索到位于伦敦的所有 Customers 所下的所有 Orders。因此,继续访问 Customer 对象的 Orders 属性不会触发新的数据库查询。

Dim db As New Northwnd("c:\northwnd.mdf")

Dim dlo As DataLoadOptions = New DataLoadOptions()
dlo.LoadWith(Of Customer)(Function(c As Customer) c.Orders)
db.LoadOptions = dlo

Dim londonCustomers = _
    From cust In db.Customers _
    Where cust.City = "London" _
    Select cust

For Each custObj In londonCustomers
    Console.WriteLine(custObj.CustomerID)
Next
Northwnd db = new Northwnd(@"c:\northwnd.mdf");
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Customer>(c => c.Orders);
db.LoadOptions = dlo;

var londonCustomers =
    from cust in db.Customers
    where cust.City == "London"
    select cust;

foreach (var custObj in londonCustomers)
{
    Console.WriteLine(custObj.CustomerID);
}

请参见

其他资源

查询数据库 (LINQ to SQL)