user7784919
user7784919

Reputation:

OrderBy an INT Column in LINQ to Entities using dynamic Expression in C#

I'm having a tables Namely StudentInfo

Table: DbSet<StudentInfo>

ID    Name
_____________________
1     Ram
2     Kumar

My C# Code is

using(var db = new Entities()) {

    Expression<Func<StudentInfo,object>> sortColumn = i => i.ID;

    IQueryable<StudentInfo> qryStudent = db.StudentInfos.Where(i => true)
                                                 .OrderBy(sortColumn);
}

Its throwing an Exception

"Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types."

If I modify the code like i => i.ID.ToString() in Expression, its working

using(var db = new Entities()) {

    Expression<Func<StudentInfo,object>> sortColumn = i => i.ID.ToString();

    IQueryable<StudentInfo> qryStudent = db.StudentInfos.Where(i => true)
                                                 .OrderBy(sortColumn);
}

How to fix this in a right way.

I need a generic solution, the Expression should be Expression<Func<StudentInfo,dynamic>> like this. It should match for both

switch(sortKey) {
    case "ID"
        sortColumn = i => i.ID;
        break;
    case "Name"
        sortColumn = i => i.Name;
        break;
}

Kindly assist me...

Upvotes: 0

Views: 912

Answers (4)

David Lebee
David Lebee

Reputation: 596

You can use this from github https://github.com/PoweredSoft/DynamicLinq

Or Nuget https://www.nuget.org/packages/PoweredSoft.DynamicLinq/

Simple Sorting

query = query.OrderByDescending("AuthorId");
query = query.ThenBy("Id");

Upvotes: 0

Vijay
Vijay

Reputation: 136

You can extend the IQueryable to add a custom OrderBy which takes the sort key like this

    public static IQueryable OrderBy(this IQueryable<StudentInfo> queryable, string sortKey)
    {
        switch (sortKey)
        {
            case "ID":
                return queryable.OrderBy(i => i.ID);
            case "Name":
                return queryable.OrderBy(i => i.Name);
        }

        return queryable;
    }

With this you can do an order by using your sort key like this

    var students = db.StudentInfos.OrderBy(sortColumn, "ID");

Upvotes: 0

S. Spindler
S. Spindler

Reputation: 546

There are some points to be considered:

  • Where(i => true) simply takes all elements, wich is not necessary
  • Why do you use the string value of your id? if it's an integer, you can change the expression to the following: Expression<Func<StudentInfo, int>> sortColumn = i => i.ID;

Please try to describe your complete problem. So it's easier to answer and you probably get help much faster :)

Upvotes: 1

Naveen Gogineni
Naveen Gogineni

Reputation: 306

Try replacing the following code:

Expression<Func<StudentInfo, object>> sortColumn = i => Convert.ToInt32(i.ID);

Problem is while converting object type of data to integer type.

Upvotes: 0

Related Questions