Tech – Noesis

The more you know, you know how little you know

Archive for March 3rd, 2008

Linq to Sql: Dynamic Sorting without using Complete Dynamic Linq Libraries

Posted by Pradeep Mishra on March 3, 2008

This problem may occur while implementing sorting in GridView. If a storedprocedure is being used either dynamic sql can be created or multiple of case statements can be used. However what if you are just using linq queries. Here are the options

  1. Using Dynamic Linq
  2. Some work arround so that linq query can be generated at runtime.

Essentially 2nd approach is the same as that used in 1st one. But if you just want to implement sorting and do not want to digg into Dynamic Linq libraries you can follow the article…

Let’s assume following method expects sortExpression parameter directly passed by UI layer GridView.

public DataTable GetSomeData(par1, par2…., string sortExpression)
{
var query = (//Linq query goes here )
// We want something like this which is not possible as of now
var query = (some query) (OrderBy SortExpression)
}
Here is the extension method you would like to follow…

public DataTable GetSomeData(par1, par2…., string sortExpression)
{
var query = (//Linq query goes here )
// We want something like this which is not possible as of now
var query = (some query) (OrderBy SortExpression)
}
public static Util
{
//Thanks to Ernesto for pointing out a small correction in method signature.
public static IQueryable OrderBy(this IQueryable source, string sortExpression) where TEntity : class
{
var type = typeof(TEntity);
// Remember that for ascending order GridView just returns the column name and for descending it returns column name followed by DESC keyword
// Therefore we need to examine the sortExpression and separate out Column Name and order (ASC/DESC)
string[] expressionParts = sortExpression.Split(‘ ‘); // Assuming sortExpression is like [ColoumnName DESC] or [ColumnName]
string orderByProperty = expressionParts[0];
string sortDirection = “ASC”;
string methodName = “OrderBy”;

//if sortDirection is descending
if (expressionParts.Length > 1 && expressionParts[1] == “DESC”)
{
sortDirection = “Descending”;
methodName += sortDirection; // Add sort direction at the end of Method name
}
var property = type.GetProperty(orderByProperty);
var parameter = Expression.Parameter(type, “p”);
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName,
new Type[] { type, property.PropertyType },
source.Expression, Expression.Quote(orderByExp));
return source.Provider.CreateQuery(resultExp);
}
}
Usage will be as of follows…

public DataTable GetSomeData(par1, par2…., string sortExpression)
{
var query = (//Linq query goes here )
// We want something like this which is not possible as of now
var query = (some query)
return query.OrderBy(SortExpression).ToDataTable(rec => new object[] { query}));
}
Again OrderBy is an extension method. Hope this helps!

Advertisements

Posted in technical | 18 Comments »

Solution to Error: The data source ‘ods_DataSource’ does not support sorting with IEnumerable data. Automatic sorting is only supported with DataView, DataTable, and DataSet.

Posted by Pradeep Mishra on March 3, 2008

Suppose you have a grid view and associated datasource as ods_DataSource.

  

<!-- Some other code---->


The select method is defined as

public ISingleResult SelectMethod(){
//Get DAL Instance DALInstance
return DALInstance.GetDATA(){}
}
Now if you try to sort on some column the following error pops up.The data source ‘ods_DataSource’ does not support sorting with IEnumerable data. Automatic sorting is only supported with DataView, DataTable, and DataSet.This is because to implement sorting you must have datasource of type DataView/DataTable/DataSet. Now if you are using traditional 3 tier architecture and returning one of these three datatypes everything works fine. The problem arises when you are using Linq. There are two possible solution for this..

  1. Implement custom sorting.
  2. Change IEnumerable datatype into one of these datatypes.

Here we will try to follow 2nd approach. In our data access layer we will change IEnumerable into a DataTable using an static utility class. Here is the code to perform that operation

public static class Util
{
public static DataTable ToDataTable(this IEnumerable varlist, CreateRowDelegate fn)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
// Could add a check to verify that there is an element 0
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
// Note that we must check a nullable type else method will throw and error
Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable)))
{
// Since all the elements have same type you can just take the first element and get type
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
//Iterate through each property in PropertyInfo
foreach (PropertyInfo pi in oProps)
{
// Handle null values accordingly
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
}
dtReturn.Rows.Add(dr);
}
return (dtReturn);
}
public delegate object[] CreateRowDelegate(T t);
}
Changes in the Select method

public ISingleResult SelectMethod(){
//Get DAL Instance DALInstance
return DALInstance.GetSomeData(){}
}
public DataTable GetSomeData()
{
ISingle result = //code to get result;
return (result.ToDataTable(rec => new object[] { result}));
}
As you can see ToDataTable is an extenstion method and will be available to all IEnumerable types.Obviously there are some performance overhead due to use of reflection but still this approach can be used. However for real time applications performance testing must be performed.

Hope this helps!

Posted in technical | Tagged: , , | 14 Comments »