Reputation:
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
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
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
Reputation: 546
There are some points to be considered:
Where(i => true)
simply takes all elements, wich is not necessaryExpression<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
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