c# - Dynamic Where condition with Queryover -
i have application , i'm trying implement ddd concepts. have repository class method list entities. know how can query queryover filter separating and operator, when parameter filled, sample
public ienumerable<product> findproducts(string name, decimal? price, datetime? validdate, int? stock, int? idsupplier) { var query = session.queryover<product>().orderby(x => x.name).asc; if (!string.isnullorempty(name)) // add condition name parameter if (price.hasvalue) // add 'and' condition price parameter if (validdate.hasvalue) // add 'and' condition validdate parameter if (idsupplier.hasvalue) // add 'and' condition idsupplier parameter // other possible conditions return query.list(); } is there way before use hql string query? hehehe
thank you!
here, use predicatebuilder:
how to:
iqueryable<product> searchproducts (params string[] keywords) { var predicate = predicatebuilder.false<product>(); foreach (string keyword in keywords) { string temp = keyword; predicate = predicate.or (p => p.description.contains (temp)); } return datacontext.products.where (predicate); } predicatebuilder source:
using system; using system.linq; using system.linq.expressions; using system.collections.generic; public static class predicatebuilder { public static expression<func<t, bool>> true<t> () { return f => true; } public static expression<func<t, bool>> false<t> () { return f => false; } public static expression<func<t, bool>> or<t> (this expression<func<t, bool>> expr1, expression<func<t, bool>> expr2) { var invokedexpr = expression.invoke (expr2, expr1.parameters.cast<expression> ()); return expression.lambda<func<t, bool>> (expression.orelse (expr1.body, invokedexpr), expr1.parameters); } public static expression<func<t, bool>> and<t> (this expression<func<t, bool>> expr1, expression<func<t, bool>> expr2) { var invokedexpr = expression.invoke (expr2, expr1.parameters.cast<expression> ()); return expression.lambda<func<t, bool>> (expression.andalso (expr1.body, invokedexpr), expr1.parameters); } } for more information on predicatebuilder , linqkit go here: http://www.albahari.com/nutshell/linqkit.aspx
Comments
Post a Comment