共用方式為


HOW TO:控制擷取的相關資料量 (LINQ to SQL)

更新: November 2007

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

注意事項:

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

範例

在下列範例中,執行查詢時,會擷取位在倫敦 (London) 之所有 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)