2015-12-24 15 views
7

Voglio ordinare la dinamica in framework di entità lambda. L'ho fondata più tempo, ma sembra non funzionare.Come ordinare dinamici nel framework di entità lambda?

////string column_name // the name of column in table <<< don't care this, I finished 
////string sort_order // ASC or DESC <<< don't care this, I finished 

using (var db = new ABCEntities()) 
{ 
    // get dynamic type of column name , but i can not 
    // ??????????? 
    var columnExp = typeof(LOCATION).GetProperty(column_name); 

    IEnumerable<LOCATION> query = db.LOCATIONs; 
    if(sort_order = "ASC") 
    { 
     query = query.OrderBy(columnExp).Tolist(); 
    } 
    else 
     query = query.OrderByDescending(columnExp).Tolist();  
} 

provo con un follow

query = db.LOCATIONs.OrderByDescending(q => q.GetType().GetProperty(column_name).GetValue(q, null)).ToList(); 

ma ottenere errore in

LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object, System.Object[])' method, and this method cannot be translated into a store expression 

Puoi dirmi qualche errore o sbagliato e come rimediare? Grazie mille.

+0

http://stackoverflow.com/questions/31955025/generate-ef-orderby-expression-by-string – Shyju

+0

ho provato, ma non è un lavoro. –

+0

@BrianCrist Si prega di essere più specifico. * Cosa * non funziona? Penso che dovresti semplicemente eseguire "OrderBy (column_name)", assumendo che tu stia usando Dynamic LINQ. –

risposta

3

Informazioni sull'uso Dynamic Linq? Può generare query da stringa.

using (var db = new ABCEntities()){ 
    var columnExp = "columnName"; 
    var query = db.LOCATIONs; 
    if(sort_order = "ASC") 
    { 
     query = query.OrderBy(columnExp).Tolist(); 
    } 
    else 
    { 
     query = query.OrderByDescending(columnExp).Tolist(); 
    } 
} 
+0

Oh, non è lavoro. Si prega di vedere il mio problema chiaramente –

+0

utilizzando Dynamic Linq e quindi modificare il codice come sopra. o incolla più del tuo codice? – kcwu

+0

Caro kcwu, la tua risposta è utile, a parte, ho fondato un modo in questo 'var propertyInfo = typeof (LOCATION) .GetProperty (columnName); query = db.LOCATIONs.AsEnumerable(). OrderByDescending (x => propertyInfo.GetValue (x, null)). ToList(); '. Grazie –

Problemi correlati