简体   繁体   中英

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?

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.

It could be better to create new Context instance for per execution;

            foreach (value in values)
            {
                using (var yourContext = new YourDbContext())
                {
                    yourContext.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()));
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM