Dynamic Linq Sorting using System.Linq.Dynamic

1

I'm trying to sort a list using the System.Linq.Dynamic library, it follows the snippet of code:

list = db.TABELA.Where(consulta.Colum + ".Contains(@0) ",     
consulta.filtro).OrderBy("@0 ", "codigo").Take(10).ToList();

but the result, in this case, is always the same, I have already tried in some ways ( DESC, ASC ), it comes the original ordering of the bank. I'm trying to sort in descending order and I can not. Can someone help me? Thank you in advance!

    
asked by anonymous 09.09.2016 / 22:02

1 answer

1

The OrderBy in your query is generating a sort of the code and not the codigo field as it is in its expression Linq Dynamic ( OrderBy("@0 ", "codigo") ), in the SQL below it is very clear:

SELECT
    [Project1].*    
    FROM ( SELECT
        N'Codigo' AS [C1],        
        FROM [dbo].[TABELA] AS [Extent1]
    )  AS [Project1]
    ORDER BY [Project1].[C1] ASC

So, to work properly, it should be:

OrderBy("Codigo ASC")

A very useful tip is to check the Entity Framework Log what is being generated :

using (MyDbContext db = new MyDbContext())
{
     db.Database.Log = c => Console.WriteLine(c);
     //...
}

In this case it generates directly in the console which SQL were generated and with this you debuga knowing the reason of the inconsistencies.

    
09.09.2016 / 23:20