优化LINQ to SQL查询

时间:2020-03-05 18:49:30  来源:igfitidea点击:

我有一个查询,看起来像这样:

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查询中带来订单及其客户?

谢谢

UDPATE:通过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。

解决方案

回答

我们可能想使用编译查询

看看http://www.3devs.com/?p=3

回答

我们还可以执行EagerLoading。在Linq2SQL中,我们可以使用LoadOptions:有关LoadOptions的更多信息
关于L2S的一个非常奇怪的事情是,我们只能在将第一个查询发送到数据库之前设置LoadOptions。