Home > Mobile >  ASP.Net Core/EF Method syntax: ignoring "orderby"?
ASP.Net Core/EF Method syntax: ignoring "orderby"?

Time:01-08

I have a C#/ASP.NET Core web app. This particular page is using LINQ/Method syntax to query the database. The query was working fine, but I'd like to return the results in sorted order.

EXAMPLE:

public async Task<IActionResult> OnGetAsync(int? id, string myFilter="showActive")
{ 
   IQueryable<EFItem> myQuery;
    switch (myFilter)
    {
        case "showAll":
            myQuery = from i in _context.EFItems orderby i.CreatedDate select i;
            break;
        case "includeSales":
            myQuery = 
                from i in _context.EFItems 
                where i.CurrentStep != "NoOpportunity"
                orderby i.CreatedDate
                select i;
            break;
        default: // "showActive"
            myQuery =
                from i in _context.HCEXPItems
                where i.CurrentStep != "Completed"
                orderby i.CreatedDate
                select i;
        break;
    }
    EFItems = await myQuery.ToListAsync<EFItem>();
    return this.Page();

Unfortunately, it seems to be ignoring orderby i.CreatedDate.

Q: What am I missing? How can I specify "orderby" within the myQuery statement?

CodePudding user response:

CAUSE:

I realized that my .cshtml page was displaying the data inside a jQuery DataTable.

The LINQ "orderby" (server side) was working fine ... but DataTable was changing the order on the client.

SOLUTION:

  1. Delete"orderby" from the LINQ query

  2. Specify an explicit sort order when initializing the DataTable:

     // Enable "Search"
     $.fn.dataTable.moment('MM/DD/YYYY');
     $('#indexTable').DataTable(
         order: [[3, 'desc']]
     );
    

CodePudding user response:

I don't fully understand why you are getting an error, but can you try the following codes?

_context.EFItems.OrderBy(x => x.CreatedDate);

_context.EFItems.Where(x => x.CurrentStep != "NoOpportunity").OrderBy(x => x.CreatedDate);

  • Related