3

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?

7
  • is something else, like other threads do something with your context? Commented Dec 13, 2017 at 5:29
  • 1
    Possible duplicate of Entity Framework Insert stored procedure in a loop Commented Dec 13, 2017 at 5:29
  • @ArjunPrakash Yes, there are recorded instances that this error is missleading Commented Dec 13, 2017 at 5:32
  • Side note: you should not use the sp_ prefix for your stored procedures. Microsoft has reserved that prefix for its own use (see Naming Stored Procedures), and you do run the risk of a name clash sometime in the future. It's also bad for your stored procedure performance. It's best to just simply avoid sp_ and use something else as a prefix - or no prefix at all! Commented Dec 13, 2017 at 5:39
  • 1
    Just guessing: is values the result of a database call? have you tried ToList() to force it to load all data? Commented Dec 13, 2017 at 5:41

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Rainman answer will probably also solve this problem but it might eat up quite a few connections
0

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()));
                }
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.