SQL statements have many functions such as Len (), now (), and so on. How to generate these functions. Recent studies have also written ways to make reference for all.
First, establish an extension class, control can only allow these functions to appear, if there are other functions directly report the exception.
1 Public Static classSqlMethods2 {3 Public Static BOOLDb_in<t> ( ThisT T, list<t> List)//inch4 {5 return true;6 }7 Public StaticBoolean db_notin<t> ( ThisT T, list<t> List)// not in8 {9 return true;Ten } One Public Static intDb_length ( This stringT//Len (); A { - return 0; - } the Public Static BOOLDb_like ( This stringTstringStr// like - { - return true; - } + Public Static BOOLDb_notlike ( This stringTstringStr// not-like - { + return true; A } at}
View Code
We're going to generate SQL, so the return value of the function is not meant to be, Len (), like, and not only for string types, in and not is for all types.
Two. Handle the logic related to different functions.
1. Determine the namespace of the class in which the function is located I'm asking for it.
2. Processing according to the name of the letter. Unexpected function throw exception occurred
The code reads "
1 Private stringDealmethodscall (methodcallexpression m_exp)2 {3 varK =M_exp;4 varg = k.arguments[0];5 ///The class name where the control function resides. 6 if(K.method.declaringtype! =typeof(sqlmethods))7 {8 Throw NewException ("function not recognized");9 }Ten Switch(K.method.name) One { A Case "Db_length": - { - varExp = k.arguments[0]; the return "LEN ("+ dealexpression (exp) +")"; - } - Case "db_in": - Case "Db_notin": + { - varEXP1 = k.arguments[0]; + varEXP2 = k.arguments[1]; A stringMethods =string. Empty; at if(K.method.name = ="inch") - { -Methods ="inch"; - } - Else - { inMethods =" not in"; - } to returnDealexpression (EXP1) + methods +dealexpression (EXP2); + } - Case "Db_like": the Case "Db_notlike": * { $ varEXP1 = k.arguments[0];Panax Notoginseng varEXP2 = k.arguments[1]; - stringMethods =string. Empty; the if(K.method.name = ="Db_like") + { AMethods =" like"; the } + Else - { $Methods =" not-like"; $ } - returnDealexpression (EXP1) + methods +dealexpression (EXP2); - the } - }Wuyi ///Unknown function the Throw NewException ("Unexpected function"); -}
working with related functions
Three. Debug results
Recently the Expressiontosql class has been sorted out for you to download reference.
Expressiontosql.zip Download
Expression to SQL (iii)--Custom function