I try to dynamically create some LINQ query for searching data in all columns.
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.