我有一个查询看起来像这样:
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
DatabaseDataContext db = new DatabaseDataContext();
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
我需要打印订单信息和创建订单的用户信息:
foreach (var o in FetchLatestOrders(0, 10))
{
Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}
这将生成一个 SQL 查询来获取订单,并为每个订单生成一个查询来获取客户信息。有没有可能优化查询,使其在一个 SQL 查询中获取订单和客户信息呢?
谢谢。
更新:根据sirrocco的建议,我将查询更改如下,它可以正常工作。只生成一个选择查询:
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
var options = new DataLoadOptions();
options.LoadWith<Post>(o => o.Customer);
using (var db = new DatabaseDataContext())
{
db.LoadOptions = options;
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
}
感谢sirrocco的帮助。