我有一个看起来像这样的查询:
public IListFetchLatestOrders(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查询?
谢谢
UDPATE:通过sirrocco的建议,我改变了这样的查询,它的工作原理.只生成一个选择查询:
public IListFetchLatestOrders(int pageIndex, int recordCount) { var options = new DataLoadOptions(); options.LoadWith (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.