c# - combine predicates into expression -
i aiming use signature:
ienumerable<t> searchfor(expression<func<t, bool>> expression);
and , these 2 predicates:
func<employee, bool> isactiveemployee = e => e.datefired == null; func<employee, bool> isnewemployee = e => e.datehired >= datetime.today.adddays(-90);
into expression. how can achieve please?
ps:
basically, trying use this. line:
var body = (binaryexpression) expression.body;
in method getdynamicquery
taken here throws exception:
unable cast object of type 'system.linq.expressions.instancemethodcallexpressionn' type 'system.linq.expressions.binaryexpression'.
using approach:
expression<func<employee, bool>> isactiveemployee = e => e.datefired == null; expression<func<employee, bool>> isnewemployee = e => e.datehired >= datetime.today.adddays(-90); expression<func<employee, bool>> combined_expression = e => isactiveemployee.invoke(e) && isnewemployee.invoke(e);
i assuming need real expression can translated sql many data access frameworks.
one solution use linqkit this:
expression<func<employee, bool>> isactiveemployee = e => e.datefired == null; expression<func<employee, bool>> isnewemployee = e => e.datehired >= datetime.today.adddays(-90); expression<func<employee, bool>> combined_expression = e => isactiveemployee.invoke(e) && isnewemployee.invoke(e);
then can wrap iqueryable
using asexpandable
method linqkit this:
var query = context.employees.asexpandable().where(combined_expression);
or, if don't want invoke asexpandable
, can expand new expression , use other expression this:
expression<func<employee, bool>> combined_expression = e => isactiveemployee.invoke(e) && isnewemployee.invoke(e); combined_expression = combined_expression.expand(); var query = context.employees.where(combined_expression);
update:
for second example provided, can this:
expression<func<employee, bool>> expression1 = e => e.guid == new guid("28d3bcfb-9472-4141-bd88-be5e7e1230f0"); expression<func<employee, bool>> expression2 = e => e.guid == new guid("0f0dba45-f842-4e46-9ed4-f50b5bcf0509"); expression<func<employee, bool>> combined_expression = e => expression1.invoke(e) || expression2.invoke(e); combined_expression = combined_expression.expand(); // use combined_expression
Comments
Post a Comment