Copy parameters from DbCommand to another DbCommand

How to 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 line.

+8
c # enterprise-library
source share
4 answers

You can put the code for reuse 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; } 
+2
source share

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()); 
+3
source share

If all you need is a parm collection, you can try a helper method that creates a deep copy of the .parameters collection in your command. See if it will spit out what you are looking for.

I can’t take credit for the ObjectCopier method, it’s just a useful base class method that I got from a previous project.

  private DbParameterCollection cloneParms(DbCommand commandWithParms) { return ObjectCopier.Clone<DbParameterCollection>(commandWithParms.Parameters); } public static class ObjectCopier { /// <summary> /// Perform a deep Copy of the object. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } } 
+1
source share
 // 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); 
+1
source share

Source: https://habr.com/ru/post/651425/


All Articles