user7784919
user7784919

Reputation:

Dynamic LINQ OrderBy for a Navigation Property using Expression in C#

I'm having two tables Namely Student and Mark

Table: DbSet<StudentInfo>

ID    Name
_____________________
1     Ram
2     Kumar
3     John

Table: DbSet<ScoreInfo>

Id    StudentId    Subject    Score
_____________________________________
1     1            GK         90
2     1            SCI        97
3     2            GK         81
4     2            SCI        99

The LINQ to SQL returns the following List

StudentId    Name    Subject    Score  
_____________________________________
1            Ram    GK         90
1            Ram    SCI        97
2            Kumar  GK         81
2            Kumar  SCI        99
3            John   null       null

The C# Code is

using(var db = new StudentEntity()) {
    var query = db.Student.Where(m => true);

    Expression<Func<StudentInfo,object>> sortExpression = null;

    if(sortColumn == "Name") {
        sortExpression = i => i.Name
    } else if(sortColumn == "Subject") {
        // ? How to achieve this
    }

    query = isAcending
                ? query.OrderBy(sortExpression)
                : query.OrderByDescending(sortExpression);

    query.Select(m => (...)).Dump();
}

The variable sortColumn is a String, which specifies the column need to sort and the variable isAcending is a bool, which specifies the sort direction.

I need to sort the Subject column. Kindly assist me how to write the Expression<Func<StudentInfo,object>> and the query should be IQueryable ?

Upvotes: 0

Views: 748

Answers (2)

James Curran
James Curran

Reputation: 103545

Exactly the way you'd write the lambda:

Expression<Func<StudentInfo,object>> sortExpression = si=>si.Name;

(Note that you can't use a var there because the compiler needs to know that you want it as an Expression<T>)

But your real problem is that you are trying to use a StudentInfo object, which you haven't created yet. First you create one, then sort by it;

 db.Mark.Select(m=> new StudentInfo {
                    StudentID = m.StudentId, 
                    Name = m.Student.Name,
                    Subject = m.Subject,
                    Score = m.Score});

Expression<Func<StudentInfo, object>> sortExpression = null;

if (sortColumn == "Name")
{
    sortExpression = i => i.Name;

}
else if (sortColumn == "Subject")
{
    sortExpression = i => i.Subject;
}

    query = isAcending
                ? query.OrderBy(sortExpression)
                : query.OrderByDescending(sortExpression);

    return query;

Upvotes: 2

Munzer
Munzer

Reputation: 2318

You can pass string to OrderBy method, something like

"colName ASC, anotherCol Desc, etc..."

you can do something like this,

string orderstring = sortColumnName +" "+ (isAcending ?? "ASC" : "DESC"); query = query.OrderBy(orderstring);

Upvotes: 0

Related Questions