Linq and dynamic sorting

Posts   
 
    
can1
User
Posts: 77
Joined: 16-Sep-2005
# Posted on: 17-Apr-2009 22:31:14   

Hello,

I am using LLBLGen 2.6 with adapter templates.

I am trying to set the order by or sort expression of linq query dynamically at run-time, on the server side, so that the query issues different 'order by' statements on the database query?

This is pretty straight forward using the standard LLBL api syntax, but can it be done using linq syntax?

Any insight would be appreciated?

Thanks.

Can1

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 18-Apr-2009 04:50:44   

Hi Can1,

You could do something like this, for example:

// create the query
LinqMetaData metaData = new LinqMetaData();
var q = from c in metaData.Customer select c;

// apply the sort later, based on some business/criteria
if (sortByCompanyName)
{
    q = q.OrderBy(c => c.CompanyName);
}
else
{
    q= q.OrderBy(c => c.Country);
}

// .. later set the adapter instance
using (DataAccessAdapter adapter = new DataAccessAdapter())
{
    ((LLBLGenProProvider2)((IQueryable)q).Provider).AdapterToUse = adapter;
    
    // ... and fetch and use the entities fetched
    foreach (CustomerEntity c in q)
    {
        Console.WriteLine("{0} - {1}", c.CompanyName, c.Country);
    }
}
David Elizondo | LLBLGen Support Team