简体   繁体   中英

How to optimize this linq query? (with OrderBy and ThenBy)

I have currently in a table about 90k rows. And it's will grow up about 1kk ~ 5kk before i execute a clean up and put all rows in a "historical table". So, when i run this following query (MyEntities is a ObjectSet):

MyEntities.Skip(amount * page).Take(amount).ToList();

This query takes about 1.2s... but when i run this following query with OrderBy and ThenBy:

MyEntities.OrderBy(b => b.Day).ThenBy(b => b.InitialHour).Skip(amount * page).Take(amount).ToList();

This query takes about 5.7s. There is a way to optimize the second query?

A few suggestions:

  • Check that it really is happening in the database (instead of fetching all entities, then sorting)
  • Make sure that both Day and InitialHour are indexed.
  • Check the generated SQL isn't doing anything crazy (check the query plan)

EDIT: Okay, so it looks like MyEntities is actually declared as IEnumerable<MyEntity> , which means everything will be done in-process... all your LINQ calls will be via Enumerable.Select etc, rather than Queryable.Select etc. Just change the declared type of MyEntities to IQueryable<MyEntity> and watch it fly...

For reading data from your DB, it's usually a good idea to create custom SQL Views, say one View per grid and one View per Form that you want to populate.

In this example, you would create a view that does the sorting for you, then map that View to an Entity in Entity Framework, then query that Entity using LINQ.

This is nice, clean, readable, maintainable and as optimal as you can make it.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM