5

I try to dynamically create some LINQ query for searching data in all columns.

enter image description here

Currently, I use the following code to build dynamic LINQ query. However, it's quite buggy when deals with complex column.

var type = property[col.ToLower()].PropertyType;
var isNullableType = type.IsGenericType && type.GetGenericTypeDefinition() == typeof (Nullable<>);

if (type.IsValueType && !isNullableType)
{
    filter += col + ".ToString().ToLower().Contains(@" + i + ".ToLower())";
}
else if (isNullableType)
{
    filter += col + ".HasValue ? " + col + ".Value.ToString().ToLower().Contains(@" + i + ".ToLower())" + " : false";
}
else
{
    filter += "(" + col + " != null ? " + col + " : \"\").ToString().ToLower().Contains(@" + i + ".ToLower())";
}

Do you have any idea to simplify my above code? I'm OK if your suggestion is work only for SQL Server 2008 or later.

Note: Column data can be any type like integer, string, object, enum and it can be null.

  • It was ok if you showed us final generated sql . – KumarHarsh Jan 03 '15 at 10:52
  • This is a common function for any data table control. There is no benefit to show you a generated SQL query. Normally, Ajax request is sent from web page. In server-side, it dynamically filter data, dynamically order data by specified column, skip and take appropriated data by specified page. –  Jan 03 '15 at 19:32

0 Answers0