i have several kind of dapper queries below, several different types result. 1 specific these, produce e.g. list<classa> :
string ansql = getsqlquerytext("query_name"); sqlconnection connection = getsqlconnection(); list<classa> result = null; try { connection.open(); result = connection.query<classa>(ansql, new //want move part here { param1 = "value1", param2 = "value2" }).tolist(); //to here out, outer call } catch //more error handling , retry logic omitted , simplified version { result = new list<classa>(); //this filled generic type } { connection.close(); } i want join kind of queries gendapperquery<t> generic method, can called of delegate (or func/action or else) (t classa or classb, etc. in final code):
list<t> result = gendapperquery<t>(() => { result = connection.query<t>(ansql, new { param1 = "value1", param2 = "value2" }).tolist(); } //and want use result specific type e.g. classa //either or after cast result[0].id = 3; //or (result list<classa>)[0].id = 3; so purpose use connection, error handling/retry logic, , of course dapper query generally, multiple times (because don't want write them down many query , type have), want (wanted) generic method somehow, query down dapper , type of (generic) list create , fill-up.
(this (wanted) generic method in same class can create connection once. error handling part more complicated, same @ every type, that's why don't want write them down multiple times. parameters can vary freely sql string inputs.)
my problem now, cannot write generic dapper query surrounding own code, specific injected function outside of (wanted) method.
is possible in c#? suggestion highly appreciated.
there many ways accomplish this. 1 mechanism create method execute/errorhandler:
public tresult executewrapper<tresult>(sqlconnection connection, func<tresult, sqlconnection> func) { tresult result; try { connection.open(); // query wrapped in function or lambda result = func(connection); } catch //more error handling , retry logic omitted , simplified version { // specifying new tresult may more difficult. either: // 1. pass default value in method parameter // result = defaultvalue; // defaultvalue method parameter // 2. use system.activator create default instance // result = (tresult)system.activator(typeof(tresult)); // original: result = new list<classa>(); // filled generic type } { connection.close(); } return result; } then use this:
list<classa> result = executewrapper(connection, (cn) => { string ansql = getsqlquerytext("query_name"); return cn.query<classa>(ansql, new { param1 = "value1", param2 = "value2" }).tolist(); });
Comments
Post a Comment