c# - Writing a basic Expression Builder -
i using linq-to-entities , 1 query requires property loaded dynamically. query looks this:
var found = context.integrateviews.groupby(x => x.typeofbed) .select(type => new typecounts { name = type.key, count = type.count() }).tolist();
the property on group clause being run typeofbed. want run query on different properties e.g., next time want run on, let's x.typeofchair , on. this, need have property in there dynamically.
i trying write expression builder this.
public expression<func<lookupfilteritem>> propertylambda(string propertyname) { var param = expression.parameter(typeof(lookupfilteritem), "lookupitem"); //type of x in above example lookupfilteritem var propertyexpression = expression.property(param, propertyname); var returnexpr = expression.lambda<func<lookupfilteritem>>(propertyexpression); return returnexpr; //if pass string "typeofbed" method, expecting return // lookupitem => lookupitem.typeofbed }
and intend use this:
var found = context.integrateviews.groupby(propertylambda("typeofbed")) .select(type => new typecounts { name = type.key, count = type.count() }).tolist();
but not working, getting compile time error says:
error cs0411: type arguments method 'system.linq.queryable.groupby(system.linq.iqueryable, system.linq.expressions.expression>)' cannot inferred usage. try specifying type arguments explicitly.
what doing wrong here?
this seems syntax issue. try this:
public expression<func<lookupfilteritem, string>> propertylambda(string propertyname) { var param = expression.parameter(typeof(lookupfilteritem), "lookupitem"); var propertyexpression = expression.property(param, propertyname); var returnexpr = expression.lambda<func<lookupfilteritem, string>>(propertyexpression, param); return returnexpr; }
and usage:
var found = context.integrateviews.groupby(propertylambda("typeofbed").compile()) .select(type => new typecounts { name = type.key, count = type.count() }).tolist();
Comments
Post a Comment