Error when running .ExecuteStoreCommand twice in one ActionResult "Parameter already used"

206 views Asked by At

I get this error, but I don't know how to clear the command object if at all possible. The idea I found on StackOverflow and am using here of 2 different parameter variables still remains glued to the first execute command. At worse I think I could split this ActionResult in half by calling two functions, each with it's own .ExecuteStoreCommand. Unless someone knows how to clear the parameter in EF? In ADO.NET it is simpler: Command.Paramters.Clear()

System.ArgumentException: The SqlParameter is already contained by another SqlParameterCollection.

var @ThisBatch= new System.Data.SqlClient.SqlParameter("ThisBatch",System.Data.SqlDbType.VarChar,3,"BactiBatchID");
@ThisBatch.Value= Session["ThisBatch"];

var sql ="UPDATE dbo.BactiBatches SET BatchStatus = 'C' WHERE BactiBatchID= @ThisBatch";

_db.ExecuteStoreCommand(sql, ThisBatch);


var @ThisBatch2 = new System.Data.SqlClient.SqlParameter("ThisBatch2", System.Data.SqlDbType.VarChar, 3, "Batch_ID");
@ThisBatch2.Value = Session["ThisBatch"];

sql = "";
sql = "UPDATE dbo.BactiBucket SET RecvDate = GetDate() WHERE Batch_ID= @ThisBatch2";


_db.ExecuteStoreCommand(sql, ThisBatch);


return RedirectToAction("AddColiform");

Edit/Update: Ok, I was able to do it like this. Not sure if there is a better answer so I will wait before answering my own question:

_db.ExecuteStoreCommand("UPDATE dbo.BactiBatches SET BatchStatus = 'C' WHERE BactiBatchID= {0}", Session["ThisBatch"]);
_db.ExecuteStoreCommand("UPDATE dbo.BactiBucket SET RecvDate = GetDate() WHERE Batch_ID={0}", Session["ThisBatch"]);

Session["ThisBatch"] = 0;
1

There are 1 answers

0
ekad On BEST ANSWER

See the second update command

var @ThisBatch2 = new System.Data.SqlClient.SqlParameter("ThisBatch2", System.Data.SqlDbType.VarChar, 3, "Batch_ID");
@ThisBatch2.Value = Session["ThisBatch"];

sql = "";
sql = "UPDATE dbo.BactiBucket SET RecvDate = GetDate() WHERE Batch_ID= @ThisBatch2";

_db.ExecuteStoreCommand(sql, ThisBatch);

I think you actually want to use ThisBatch2 instead of ThisBatch as the second parameter of _db.ExecuteStoreCommand method, so change it to ThisBatch2.

var @ThisBatch2 = new System.Data.SqlClient.SqlParameter("ThisBatch2", System.Data.SqlDbType.VarChar, 3, "Batch_ID");
@ThisBatch2.Value = Session["ThisBatch"];

sql = "";
sql = "UPDATE dbo.BactiBucket SET RecvDate = GetDate() WHERE Batch_ID= @ThisBatch2";

_db.ExecuteStoreCommand(sql, ThisBatch2);