提高Linq to Sql 性能笔记

1.使用DataLoadOptions的 LoadWith ,AssociateWith方法

使用LoadWith 连接一次数据库便可获得产品以及相关订单 

       ProductDataContext orderDC= new ProductDataContext();
            DataLoadOptions dataLoadOption = new DataLoadOptions();
            dataLoadOption.LoadWith<Product>(p => p.Orders);
            orderDC.LoadOptions = dataLoadOption;

使用 AssociateWith 方法指定子查询。

Northwnd db = new Northwnd(@"c:\northwnd.mdf");
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;

foreach (Customer custObj in custOrderQuery)
{
    Console.WriteLine(custObj.CustomerID);
    foreach (Order ord in custObj.Orders)
    {
        Console.WriteLine("\t {0}",ord.OrderDate);
    } 
}
MSDN:http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.associatewith.aspx

2.使用CompiledQuery.Compile

 

        Func<LinqObjectDataContext, string, IQueryable<product>> q =

    CompiledQuery.Compile<LinqObjectDataContext, string, IQueryable<product>>

        ((LinqObjectDataContext nw, string name) =>

            from o in nw.Products

            where o.ProductName==name

            select o);
MSDN:http://msdn.microsoft.com/en-us/library/bb548979.aspx

 

 

3:当只需检索数据时设置 ObjectTrackingEnabled=false

posted on 2010-12-17 11:21  jh_x  阅读(552)  评论(0编辑  收藏  举报

导航