Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Order By not working

The Linq query "order by" is not working and I've followed all the suggestions found on your site and other sites. Any assistance would be appreciated.

    [WebGet]
    public IQueryable<vw_providercharge_providers> GetChargeProviders(int submitted)
    {
        var results = (from p in this.CurrentDataSource.vw_providercharge_providers
                       where p.submitted == submitted
                       orderby p.fullname
                       select p);
        return results;
    }

Thanks for your input!

Yes, this is a WebGet method for a WCF data service. I get a 400 error if I don't return an IQueryable type, so I modified your suggestion a little. Unfortunately, it still seems to disregard any order-by.

[WebGet]
public IQueryable<vw_providercharge_providers> GetChargeProviders(int submitted)
{
    var results = (from p in this.CurrentDataSource.vw_providercharge_providers
                   where p.submitted == submitted
                   orderby p.fullname
                   select p).ToArray();
    results.OrderBy(p => p.patientname);
    return results;
}
like image 708
user680891 Avatar asked Jun 23 '11 19:06

user680891


3 Answers

I notice you return an IQueryable<T> - are you calling any LINQ methods on the result before you enumerate it?

Not all LINQ methods preserve order. Most commonly, calling Distinct() after you do the ordering will destroy the order.

like image 152
BlueRaja - Danny Pflughoeft Avatar answered Nov 20 '22 15:11

BlueRaja - Danny Pflughoeft


Since your method is a marked with a WebGet attribute, I'm assuming that you are calling this method from a Web endpoint, therefore you may need to collapse the collection prior to send it through internet.

Try:

[WebGet]
public vw_providercharge_providers[] GetChargeProviders(int submitted)
{
    var results = (from p in this.CurrentDataSource.vw_providercharge_providers
                   where p.submitted == submitted
                   orderby p.fullname
                   select p).ToArray();
    return results;
}

This way you have the guarantee that the GetChargeProviders method returns and array instead of an linq expression.

Regards,

like image 31
wacdany Avatar answered Nov 20 '22 13:11

wacdany


I found the cause of the issue.

I had not set the "fullname" column as an Entity Key for the "vw_providercharge_providers" data model entity. Only the identity column was set as an Entity Key. I didn't realize that was a requirement to use it in an order by clause.

Thanks again for your input.

like image 20
user680891 Avatar answered Nov 20 '22 15:11

user680891