作法:控制擷取的相關資料多寡

使用 LoadWith 方法可指定與您主要目標有關、應該同時擷取的資料。 例如,如果您預先得知需要客戶訂單的相關資訊,則可以使用 LoadWith,以確保在擷取客戶資訊的同時也會擷取訂單資訊。 這種方法只要存取一次資料庫,就可以同時取得兩個資訊集。

注意

您可以將叉積擷取為一個大型投影 (如在找到客戶時擷取訂單),以擷取與查詢之主要目標相關的資料。 但是這種方法通常有其缺點。 例如,其結果只是投影,而不是 LINQ to SQL 可以變更和持續的實體。 而且您可能會擷取到很多不需要的資料。

範例

在下列範例中,執行查詢時,會擷取位在倫敦 (London) 之所有 Orders 的所有 Customers。 如此一來,後續存取 Orders 物件上的 Customer 屬性時,便不會觸發新的資料庫查詢。

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

另請參閱