提高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;
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
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);
}
}
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
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);
语言集成查询(Language Integrated Query, LINQ),发音 "link",是一项微软技术,新增一种自然查询的SQL语法到.NET Framework 的编程语言中,目前可支持 Visual Basic .NET 以及 C# 语言。
浙公网安备 33010602011771号