Copy parameters from DbCommand to another DbCommand

Aivan Monceller picture Aivan Monceller · Jan 24, 2011 · Viewed 8.4k times · Source

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.

Answer

Alexey picture Alexey · Nov 6, 2014
// 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);