Home > other >  How to apply the order by outside of the SQL query (that is - at application level instead of the SQ
How to apply the order by outside of the SQL query (that is - at application level instead of the SQ

Time:01-29

var data = await _context.myData.AsNoTracking()                            
   .Where(usr=>usr.User.Profile.Email==email)
   .Select(usr=>new myDTO
     {
       uID=usr.Id,
       uname=usr.Name,
     })
   .OrderByDescending(usr => usr.DateReg)
   .ToListAsync();

I am writing query using the entity framework. This will perform the order by sorting at the SQL server level.

How to do the sorting at the application level instead?

I tried .ToListAsync().OrderBy... but there is no method like OrderBy.. on ToListAsync()

CodePudding user response:

I'm not entirely sure why you would want to order in memory rather than let the DB do it, other than trying to order based on something that EF cannot translate down to SQL. However to do so:

var data = await _context.myData.AsNoTracking()                            
   .Where(usr=>usr.User.Profile.Email==email)
   .Select(usr=>new myDTO
     {
       uID=usr.Id,
       uname=usr.Name,
       DateReg = usr.Datereg
     })
   .ToListAsync();

var orderedData = data.OrderByDescending(usr => usr.DateReg);

Since you are projecting to a DTO you need to include anything you would be using for the ordering in the DTO as data will be a List<myDTO>, and not have access to the entity.

Generally speaking unless you must order in memory due to something like calling a calculation or such that absolutely cannot be rewritten in a way that could be sent to SQL, it is generally much better to let the database do the ordering. Any question of performance for the underlying query can often be resolved by looking at the execution plan and tuning indexes.

  •  Tags:  
  • Related