Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy parameters from DbCommand to another DbCommand

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.

like image 519
Aivan Monceller Avatar asked Jan 24 '11 04:01

Aivan Monceller


3 Answers

// 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);
like image 170
Alexey Avatar answered Nov 16 '22 05:11

Alexey


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;
}
like image 26
Kevin Stricker Avatar answered Nov 16 '22 07:11

Kevin Stricker


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());
like image 2
Divi Avatar answered Nov 16 '22 06:11

Divi