LINQ – 使用DataLoadOptions 提高LINQ to SQL 查询性能
EntLib.com开源小组发表,http://www.EntLib.com,2008-7-2
LINQ to SQL 提供了 DataLoadOptions用于立即加载对象,避免往返访问数据库,提高查询性能。方法包括:
LoadWith 方法,用于立即加载与主目标相关的数据。
AssociateWith 方法,用于筛选为特定关系检索到的对象。
如下LINQ to SQL代码示例:
OrderDataContext orderDC;
orderDC = new OrderDataContext();
orderDC.Log = Console.Out;
DataLoadOptions dataLoadOption = new DataLoadOptions();
dataLoadOption.LoadWith<Order>(r => r.Order_Details);
orderDC.LoadOptions = dataLoadOption;
var query = from ord in orderDC.Orders
select ord;
grdOrder.DataSource = query;
grdOrderDetail.DataSource = grdOrder.DataSource;
grdOrderDetail.DataMember = "Order_Details";
通过使用LoadWith 方法指定应同时检索与主目标Order相关的Order Detail 数据,这样后续的查询方法仅访问一次数据库,并可同时获取Order、Order Detail 的所有信息。
如下是输出的SQL脚本:
SELECT [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode], [t0].[ShipCountry], [t1].[OrderID] AS [OrderID2], [t1].[ProductID], [t1].[UnitPrice], [t1].[Quantity], [t1].[Discount], (
SELECT COUNT(*)
FROM [dbo].[Order Details] AS [t2]
WHERE [t2].[OrderID] = [t0].[OrderID]
) AS [value]
FROM [dbo].[Orders] AS [t0]
LEFT OUTER JOIN [dbo].[Order Details] AS [t1] ON [t1].[OrderID] = [t0].[OrderID]
ORDER BY [t0].[OrderID], [t1].[ProductID]
使用 AssociateWith 方法指定子查询以限制检索的数据量。
在下面的示例中,AssociateWith 方法将检索的 Orders 限制为当天尚未装运的那些 Orders。如果没有此方法,则会检索所有 Orders,即使只需要一个子集。
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;