question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Support SaveChanges while iterating a query

See original GitHub issue
using (var db = new UnicornStoreContext())
{
    foreach (var p in db.Products)
    {
        db.Products.Add(new Product { DisplayName = "Copy of " + p.DisplayName });
        db.SaveChanges();
    }
}

SqlException: New transaction is not allowed because there are other threads running in the session. System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

Obviously this is a bit of an anti-pattern since the SaveChanges should go outside the loop, but this is just a boiled down repro from a case where it does make sense (calling another component like Idenitty that saves to the database as part of the API call).

foreach (var role in db.PreApprovals
    .Where(p => p.UserEmail == user.Email)
    .Select(p => p.Role))
{
    await UserManager.AddToRoleAsync(user, role);
}

Model from the repro…

    public class UnicornStoreContext : DbContext
    {
        public DbSet<Product> Products { get; set; }

        protected override void OnConfiguring(DbContextOptions options)
        {
            options.UseSqlServer("Server=(localdb)\\v11.0;Database=UnicornStore;Trusted_Connection=True;MultipleActiveResultSets=true");
        }
    }

    public class Product
    {
        public int ProductId { get; set; }
        public string DisplayName { get; set; }
        public string Description { get; set; }
        public decimal MSRP { get; set; }
        public decimal CurrentPrice { get; set; }
    }

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:8 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
ajcvickerscommented, Jul 10, 2020

@dazbradbury I read through to understand again. I don’t think it’s something we are planning to revisit.

0reactions
dazbradburycommented, Jul 10, 2020

Understood. We’re happy to rely on the analyser, I guess if anyone else runs into this they can comment / follow this issue. Thanks for letting us know in any case so we can plan around it.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Entity Framework - Loop then call SaveChanges
Note : SaveChanges() operates within a transaction. SaveChanges() will roll back that transaction and throw an exception if any of the dirty ...
Read more >
Entity Framework doesn't like SaveChanges in a for loop.. ...
So I'm working on a program which is a service that loops through records and calculates averages and then saves the changes to...
Read more >
Async query and save - EF6
SaveChanges begins to push the new Blog to the database; SaveChanges completes; Query for all Blogs is sent to the database; Query returns...
Read more >
ExecuteUpdate and ExecuteDelete - EF Core
ExecuteUpdate and ExecuteDelete are a way to save data to the database without using EF's traditional change tracking and SaveChanges() ...
Read more >
Gotcha: Entity Framework gets slow in long Iteration Loops
I've been running into a common issue with Entity Framework where using a dbContext through many context operations can drastically slow ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found