标签云

微信群

扫码加入我们

WeChat QR Code

I have a query that looks like this:

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();
}

I need to print the information of the order and the user who created it:

foreach (var o in FetchLatestOrders(0, 10))
{
    Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}

This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query?

Thanks

UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated:

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();
    }
}

Thanks sirrocco.


Wow, this was great. i implemented this and the query time reduced from 25 seconds to 1.5.. great info thanks.

2018年08月16日12分25秒

Could you please answer stackoverflow.com/questions/11262785/… ?

2018年08月16日12分25秒