var age=23;var name= "Zhang";
StringBuilder condition =NewStringBuilder (); Condition. Append ("where 1=1"); Dynamicparameters P=Newdynamicparameters (); if(age>0) {condition. Append ("and age> @age"); P.add ("@age", age, System.Data.DbType.String);//For the Add method, the first argument can be without the @ prefix, the source code has substring (1), it is processed}if(!string. Isnullorwhitespace (name))//{condition. Append ("and chinesename like @name"); P.add ("@name", "%" +name+"% ", System.Data.DbType.String);//For the like statement, the source code is a bug or deliberately not handled? This must be tiled% } using(varconn =connectionfactory.getopenconnection ()) { varResult= Conn. Getlist<t>(conditions,parameters); }
Note the above two questions:
1, for like statement, stitching%
2,add method can not add @ prefix, the source code is as follows, will handle
Static stringClean (stringname) { if(!string. IsNullOrEmpty (name)) {Switch(name[0]) { Case '@': Case ':': Case '?': returnName. Substring (1); } } returnname; }
Dapper using dynamicparameters to construct dynamic parameter query