2010-05-22 51 views
20

loadwith和associatewith之間有什麼區別。從我閱讀的文章看來,loadwith用於加載附加數據(例如客戶的所有訂單)。而AssociateWith則用於過濾數據。linq to sql loadwith vs associatewith

這是一個正確的理解?如果有人能夠用基於示例的解釋來解釋這個問題,它也會很好。

回答

30

LoadWith用於關聯的執行急切負載而不是默認延遲加載

通常情況下,第一次引用它們時會加載關聯。這意味着如果您選擇100 Order實例,然後對它們的每個Details執行一些操作,那麼實際上您將對數據庫執行101 SELECT操作。另一方面,如果LoadOptions指定爲LoadWith<Order>(o => o.Details),則全部在單個SELECT中完成,並添加JOIN

AssociateWith關聯時被加載,只是什麼加載不會對任何影響。每次加載關聯時,它都會添加WHERE子句。

如您所說,AssociateWith用於自動過濾器數據。通常,如果您知道關聯具有非常多的元素並且只需要它們的特定子集,就可以使用它。同樣,它主要是性能優化,只是一種不同的類型。

+6

這一行對我來說很清楚「AssociateWith對關聯何時加載沒有任何影響,只是加載了什麼」。 謝謝。 – stackoverflowuser 2010-05-22 17:14:03

7

是的,你的理解是正確的; AssociateWith在查詢之前過濾數據,而LoadWith在查詢中返回關聯的對象。做LoadWith的原因是你可以用1個查詢返回關聯的對象。否則額外的數據庫調用將在您迭代關聯的對象時進行。

親自嘗試不同的示例,並查看通過Profiler或其他記錄器生成的SQL。請記住,在執行任何查詢之前,需要在DataContext上設置這些選項。

看看下面的鏈接(MSDN)中的例子。我剛剛複製了他們在那裏使用的示例。

LoadWith

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; 

AssociateWith

DataLoadOptions dlo = new DataLoadOptions(); 
dlo.AssociateWith<Customer>(
    c => c.Orders.Where(p => p.ShippedDate != DateTime.Today)); 
db.LoadOptions = dlo; 

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