Created
December 17, 2010 23:33
-
-
Save juanplopes/745903 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class MontaFiltro<T, P> | |
where P : DbParameter, new() | |
{ | |
public static string RetornaWhere(T obj, out List<P> parameters) | |
{ | |
parameters = new List<P>(); | |
var where = new List<string>(); | |
foreach (var property in obj.GetType().GetProperties()) | |
{ | |
var tableFilter = GetAttributeFrom(property); | |
var valor = GetValueFrom(obj, property); | |
if (HasNoValue(valor) || MustBeIgnored(tableFilter, valor) || ValueIsEmptyDateTime(property, valor)) | |
continue; | |
if (IsDateTimeLast(property, tableFilter)) | |
valor = AddAlmostOneDayTo(valor); | |
if (tableFilter.IsLikeCommand) | |
valor = "%" + valor + "%"; | |
where.Add(string.Format("{0}.{1} {2} :{3}", tableFilter.TableName, tableFilter.ColumnName, tableFilter.Operacao, tableFilter.ParamName)); | |
AddParameterTo(parameters, tableFilter, valor); | |
} | |
if (where.Any()) | |
return string.Join(" AND ", where.ToArray()) | |
else | |
return string.Empty; | |
} | |
private static void AddParameterTo(List<P> parameters, TableFilter tableFilter, object valor) | |
{ | |
parameters.Add(new P { ParameterName = ":" + tableFilter.ParamName, Value = valor }); | |
} | |
private static object AddAlmostOneDayTo(object valor) | |
{ | |
var dateTime = Convert.ToDateTime(valor); | |
valor = dateTime.AddHours(23).AddMinutes(59).AddSeconds(59); | |
return valor; | |
} | |
private static bool IsDateTimeLast(System.Reflection.PropertyInfo property, TableFilter tableFilter) | |
{ | |
return property.PropertyType.Equals(typeof(DateTime)) && tableFilter.IsDataTimeLast; | |
} | |
private static bool ValueIsEmptyDateTime(System.Reflection.PropertyInfo property, object valor) | |
{ | |
return property.PropertyType.Equals(typeof(DateTime)) && valor.Equals(DateTime.MinValue); | |
} | |
private static bool MustBeIgnored(TableFilter tableFilter, object valor) | |
{ | |
return !string.IsNullOrEmpty(tableFilter.IgnoreValue) && valor.ToString().Equals(tableFilter.IgnoreValue); | |
} | |
private static bool HasNoValue(object valor) | |
{ | |
return valor == null || string.IsNullOrEmpty(valor.ToString()); | |
} | |
private static object GetValueFrom(T obj, System.Reflection.PropertyInfo property) | |
{ | |
var valor = property.GetValue(obj, null); | |
return valor; | |
} | |
private static TableFilter GetAttributeFrom(System.Reflection.PropertyInfo property) | |
{ | |
var tableFilter = property.GetCustomAttributes(typeof(TableFilter), false)[0] as TableFilter; | |
return tableFilter; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment