开发者

Speeding up LinqDataSource

开发者 https://www.devze.com 2023-02-15 01:30 出处:网络
Greetings, I have a following question. Suppose where are two tables in the database: Clients( id, name,

Greetings, I have a following question. Suppose where are two tables in the database:

Clients(
  id,
  name,
  address)

Orders(
  id,
  name,
  desc,
  datemodified,
  client_id)

The second one references the first one, that is each order is assigned to the client. Now suppose I have an .aspx page with a LinqDataSource for Orders table, and a GridView that uses this datasource and displays a table with a following columns:

  1. Order name.
  2. Order desc.
  3. Client name.
  4. Client address.

As far as I understand, the Linq to SQL is designed in such a way, that by default it does not load any associated entities, it only does it when a child property is requested. So, when a page is loaded, the following situation will occur:

  1. First query will retrieve the records from the Order开发者_开发技巧s table.
  2. For each row displayed by GridView an additional query will be performed when one of the client properties is requested.

Therefore, if we have 100 orders, this means will perform 101 queries instead of one (or even maybe 201, if a query will be performed for each client property)? How to avoid this and make LinqDataSource load all the required fields by a single query?

Right now I see the only workaround for this problem - use an SqlDataSource with a join query, that will retrieve all required fields at once.


Set the LoadOptions in the LinqDataSource.ContextCreated Event

Have a look here how to do it http://codebetter.com/davidhayden/2007/08/06/linq-to-sql-query-tuning-for-performance-optimization/


You could override the OnSelecting event of the LinqDataSource to have it retrieve an anonymous type with the exact data you are looking for:

protected void LinqDataSource_OnSelecting(object sender, LinqDataSourceSelectEventArgs e)
{
    DataContext dc = new DataContext();
    var query = from o in dc.Orders
                select new
                {
                    OrderName = o.name,
                    OrderDesc = o.desc,
                    ClientName = o.Client.name,
                    ClientAddress = o.Client.address
                };
    // Insert any necessary conditional statements adjustments as needed.

    e.Result = query;
}

The query it will send to the database will grab only those four fields, and do it with an inner join, so you'll only retrieve data once for each row.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号