Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

entity framework - Linq Order by when column name is dynamic and pass as a string to a function

I have a Linq (Entity Framework) Query as

function getData(string col_to_sort , bool IsAscending , int pageNo , int pageSize)
{
  context.table_name.Skip(pageNo*pageSize).Take(pageSize).ToArray();
}

What i want is that if i pass the name of the column as a parameter to the function and the order it will sort my query too.

Since my column name will be a string so we might need to convert it to ObjectQuery.

How can i achieve this?

Any help is appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Dynamic Linq:

string direction = IsAscending ? " ASC" : " DESC";
context.table_name.OrderBy(col_to_sort + direction).Skip(pageNo*pageSize).Take(pageSize).ToArray();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...