Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework execute stored procedure in a loop

I am trying to loop through a list and execute a stored procedure on every item in the list.

foreach(value in values) {
    Context.Database
        .ExecuteSqlCommand(
            "sp_ProcedureName @value1, @value2, @value3",
            new SqlParameter("@value1", value.value1.ToString()),
            new SqlParameter("@value2", value.value2.ToString()),
            new SqlParameter("@value3", value.value3.ToString()));
}

I keep getting the following error:

New transaction is not allowed because there are other threads running in the session.

I tried to use the async method as well. But that didn't seem to work. Is there something I am missing. Or is it not possible to run a stored procedure inside a loop?

like image 538
Dblock247 Avatar asked Nov 27 '25 12:11

Dblock247


1 Answers

Perhaps the db call to populate values has opened a transaction, stopping the inside call functioning.

Try using .ToList() in the call that populates values to preload all of the values first.

like image 160
Nick.McDermaid Avatar answered Nov 30 '25 00:11

Nick.McDermaid