How do you copy DbCommand
parameters to another DbCommand
, I want a new DbCommand
with the same parameters as my last DbCommand
. But now with a different sql string.
// Copy parameters from cmd1 to cmd2
// Creates an array with new parameters
var nsp = cmd1.Parameters.Cast<ICloneable>().Select(x => x.Clone() as SqlParameter).Where(x => x != null).ToArray();
// Copy parameters into another command
cmd2.Parameters.AddRange(nsp);
You could put the code you need to re-use in a separate method:
public DbCommand RecycledParameters(string sql, IList<DbParameter> parameters)
{
var result = db.GetSqlStringCommand(sql);
foreach(DbParameter p in parameters)
{
db.AddInParameter(result, p.ParameterName, p.DbType, p.Value);
}
return result;
}
could you do something like this?
System.Data.Common.DbCommand command = new System.Data.SqlClient.SqlCommand();
System.Data.Common.DbCommand command1 = new System.Data.SqlClient.SqlCommand();
command1.Parameters.AddRange(command.Parameters.Cast<System.Data.Common.DbParameter>().ToArray());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With