c# - How to update a poco with Enterprise-Library 5.0 -
i pass poco properties stored procedure (update , add object) earlier versions of enterprise library (e.g. v2.0) can this:
var arrparam = sqlhelperparametercache.getspparameterset(connectionstring(), sprocnameset); (int x = 0; x <= arrparam.length - 1; x++) { system.reflection.propertyinfo pi = dataobject.gettype() .getproperty(arrparam[x].parametername .substring(1, convert.toint32(arrparam[x].parametername.length) - 1)); arrparam[x].value = pi.getvalue(mydataobject, null); } sqlhelper.executescalar(connectionstring(), commandtype.storedprocedure, sprocnameset, arrparam);
but version 5.0 (maybe earlier?) sqlhelperparametercache.getspparameterset method gone.
the question is: how can stored-proc-parameters , fill these poco-properties-values?
you can this:
database db = databasefactory.createdatabase(); string spname = "mysp"; var parameters = new object[] { "information", 22 }; int value = (int)db.executescalar(spname, parameters);
now, relies on parameter order. if want use names , auto populate dbcommand , database supports parameter discovery (e.g. sql server) like:
public class myclass { public string severity { get; set; } public int othervalue { get; set; } } myclass myclass = new myclass() { othervalue = 1, severity = "information" }; database db = databasefactory.createdatabase(); string spname = "mysp"; dbcommand cmd = db.getstoredproccommand(spname); db.populatecommandvalues(cmd, myclass); int value = (int)db.executescalar(cmd);
public static class databaseextensions { public static void populatecommandvalues<t>(this database db, dbcommand cmd, t poco) { if (!db.supportsparemeterdiscovery) { throw new invalidoperationexception("database not support parameter discovery"); } db.discoverparameters(cmd); foreach (dbparameter parameter in cmd.parameters) { if (parameter.direction != system.data.parameterdirection.output && parameter.direction != system.data.parameterdirection.returnvalue) { propertyinfo pi = poco.gettype().getproperty( parameter.parametername.substring(1)); // remove @ parameter if (pi != null) { parameter.value = pi.getvalue(poco, null); } } } } }
this assumes poco property names same stored procedure parameter names.
Comments
Post a Comment