Hey Fabio,
thanks for that- it made me go and look on the differences between
IEnumerable<T> and IQueryable<T>, so I had a very important lesson as
well :)
As for my question, here's a piece of code I just wrote to express
better what I have in mind.
I'd be, yet again, more than grateful to get any feedback and ideas-
does this make any sense??
Or would having a method in my DAL per search criteria that returns an
IQueryable<TEntity> would be easier to maintain?
public static class ExpressionCriteriaExtensions
{
public static Expression<Func<T, bool>> GetCriteria<T>(this
Expression<Func<T, bool>> ret, T instance, params Expression<Func<T,
object>>[] criteriaProperties)
{
foreach (var expression in criteriaProperties)
{
Func<T, object> func = expression.Compile();
object propertyValue = func(instance);
ret = ret.GetStringEqCriteria(func, propertyValue);
ret = ret.GetDateEqCriteria(func, propertyValue);
}
return ret;
}
private static Expression<Func<T, bool>> GetStringEqCriteria<T>
(this Expression<Func<T, bool>> ret, Func<T, object> func, object
propertyValue)
{
string stringValue = propertyValue as string;
if (!string.IsNullOrEmpty(stringValue))
{
Func<T, object> tmp = func;
if (tmp != null)
{
if (ret == null) ret = t => tmp(t) == stringValue;
else
{
Func<T, bool> currentCriteria = ret.Compile();
ret = t => currentCriteria(t) && tmp(t) ==
stringValue;
}
}
}
return ret;
}
private static Expression<Func<T, bool>> GetDateEqCriteria<T>
(this Expression<Func<T, bool>> ret, Func<T, object> func, object
propertyValue)
{
if (propertyValue is DateTime)
{
DateTime dateTimeValue = (DateTime)propertyValue;
Func<T, object> tmp = func;
if (tmp != null)
{
if (ret == null) ret = t => (DateTime)tmp(t) ==
dateTimeValue;
else
{
Func<T, bool> currentCriteria = ret.Compile();
ret = t => currentCriteria(t) && (DateTime)tmp
(t) == dateTimeValue;
}
}
}
return ret;
}
}
On the service, this would be called like that:
Expression<Func<User,bool>> criteria = null;
criteria = criteria.GetCriteria(user, u => u.Name, u => u.Birthdate);
List<User> list = myDal.GetBy(criteria);
and in MyDal I'll have this:
public IList<User> GetBy(Expression<Func<User, bool>> criteria)
{
return Session.Linq<User>().Where(criteria).ToList();
}
On Nov 13, 11:59 pm, Fabio Maulo <
fabioma...@gmail.com> wrote:
> btw should be
> Expression<Func<TEntity, bool>> predicate
> to be used as
> Session.Linq<User>.Where(predicate)
>
> 2009/11/13 Nieve <
nieveg...@gmail.com>