简体   繁体   中英

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 ?

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;

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM