c# - Linq-SQL Generic GetById with a custom Expression -
i've created generic target tables in database. i've added generic .where() expression containing 1 parameter in lambda expression. there way can add more 1 parameter in same expression? please ignore fact below method returns 1 item, make return ilist.
here's method:
public virtual t getbyid( int32 id, string somestringcolumn ) { parameterexpression itemparameter = expression.parameter( typeof( t ), "item" ); var whereexpression = expression.lambda<func<t, boolean>> ( expression.equal( expression.property( itemparameter, "id" ), expression.constant( id ) ), new[] { itemparameter } ); return context.set<t>().where( whereexpression ).firstordefault(); }
my actual intentions method later perform contains() on "string" properties of target table "t". below , append above expression check if string property contains value in "somestringcolumn". insight, "somestringcolumn" general search string on page past ajax on every back-end call.
var properties = item.gettype().getproperties().where( p => p.propertytype == typeof( string ) ).toarray(); ( int32 = 0; < properties.length; i++ ) { }
i'm trying achieve in non-generic method:
public override list<tableindatabase> list( pagingmodel pm, customsearchmodel csm ) { string[] qs = ( pm.query ?? "" ).split( ' ' ); return context.tableindatabase .where( t => ( qs.any( q => q != "" ) ? qs.contains( t.columnname) : true ) ) .orderby( string.format( "{0} {1}", pm.sortby, pm.sort ) ) .skip( pm.skip ) .take( pm.take ) .tolist(); }
if understand correctly, seeking this:
var item = expression.parameter(typeof(t), "item"); expression body = expression.equal(expression.property(item, "id"), expression.constant(id)); if (!string.isnullorempty(somestringcolumn)) { var properties = typeof(t).getproperties().where(p => p.propertytype == typeof(string)).tolist(); if (properties.any()) body = expression.andalso(body, properties.select(p => (expression)expression.call( expression.property(item, p), "contains", type.emptytypes, expression.constant(somestringcolumn)) ).aggregate(expression.orelse)); } var whereexpression = expression.lambda<func<t, bool>>(body, item);
i.e. build contains
expression each string property, combine them using or
, combine result first condition using and
.
Comments
Post a Comment