When using DbContextOptionsBuilder.UseModel with a singleton Instance, EF crashes when trying to initialize the model in multiple threads #25205
Labels
area-model-building
closed-fixed
The issue has been fixed and is/will be included in the release indicated by the issue milestone.
customer-reported
type-bug
Milestone
Here is my OnConfiguring logic in my DbContext class:
The IModel being generated is a static singleton that was generated by the dotnet ef dbcontext optimize command line tool.
I am running a console application that generates multiple threads, and each thread creates a new DbContext and fetches data from the db. That code looks like this:
When I run this code, eventually, I get a crash with this call-stack:
The call stack is too large to post here, so I cut it off for brevity, however, I do believe that the above exception is easily reproducable in any db.
I'm happy to zip up and attach a small project, however, I'm not sure how to get a Db included with this bug ticket.
I believe the issue is that the .UseModel(dbModel) call that is happening across the threads will all run initialization code against the same instance of the IModel, and that, at this point is NOT thread safe. If for example, you uncomment the first commented line in the sample code above, then the code works ok because the first line causes the singleton model to be initialized fully without other threads trying to do the same.
Include provider and version information
EF Core version: 6.0.0-preview.7.21355.1
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6.0
Operating system: Windows 10
IDE: Visual Studio 2022 17.0.0 preview 1.1
The text was updated successfully, but these errors were encountered: