c# - Using the logic from one lambda within a second lambda -
i've looked @ other questions around , can't work out how apply answers particular situation. have couple of models this:
public class person { public int personid { get; set; } } public class business { public int businessid { get; set; } }
i want able write couple of different generic methods: 1 gets models using provided lambda might this:
getwhere(p => p.personid == 1)
and 1 models using unique key - make flexible, i'd able specify unique key using lambda:
getbyuniquekey(p => p.personid, 1)
or
getbyuniquekey(b => b.businessid, 1)
ideally getbyuniquekey
shorthand method build expression send getwhere
, , return firstordefault() result. logic escaping me. want do:
public ienumerable<tmodel> getwhere(expression<func<tmodel, bool>> whereexpression) { // db using expression provided } public tmodel getbyuniquekey<tuniquekey>( expression<func<tmodel, tuniquekey>> uniquekeyproperty, tuniquekey value) { return getwhere(m => uniquekeyproperty(m) == value).firstordefault(); }
so want take uniquekeyproperty
expression, invoke on supplied parameter somehow property, , use property in whereexpression
expression.
a note on duplicate questions: know looks duplicate of other similar questions, please note have read , can't figure out how apply answers specific use case.
some clarification in response comments:
put simply, want following:
i want take expression p => p.personid
, value 1, , generate whereexpression
looks p => p.personid == 1
. (thanks @rob)
you can build new expression key selector , value provided so:
public tmodel getbyuniquekey<tuniquekey>( expression<func<tmodel, tuniquekey>> uniquekeyselector, tuniquekey value) { return getwhere(expression.lambda<func<tmodel,bool>>( expression.makebinary( expressiontype.equal, uniquekeyselector.body, expression.constant(value, typeof(tuniquekey))), uniquekeyselector.parameters)); }
for querying id wouldn't bother approach. check out other static methods on expression class.
Comments
Post a Comment