LINQ – 使用DataLoadOptions 提高LINQ to SQL 查询性能

本文介绍了如何使用LINQtoSQL中的DataLoadOptions来优化查询性能。通过LoadWith方法可以一次性加载主表及其关联表数据,减少数据库访问次数;而AssociateWith方法则能限制子查询数据量,进一步提高查询效率。
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;
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值