I have an existing EF DbContext class (SyncContext) that is generated from a SQL database. In my unit tests, I use SQLite to not have an external dependency on SQL. Problem is the SQL database has tables without keys which SQLite will not allow. In order to work around this I inherit from the SyncContext class (TestSyncContext), and override the OnModelCreating method and manually define fields as keys. This was working great until I ran into an issue where I needed to have different keys for different tests, since I was testing having rows with duplicate values for the key column in the table (DupKeyTest). I added a way to be able to define different keys in the OnModelCreating for each test. When I run the tests individually, everything works fine. When I run the test with other tests, it errors because the OnModelCreating isn't getting called with the different keys for the DupKeyTest. I finally traced it down to the ServiceProviderCache caching the DbContextOptions, and resolved my issue by adding this code directly before my context.Database.EnsureCreated:
var field = ServiceProviderCache.Instance.GetType().GetField("_configurations", BindingFlags.NonPublic | BindingFlags.Instance);
var dict = (ConcurrentDictionary<IDbContextOptions, (IServiceProvider ServiceProvider, IDictionary<string, string> DebugInfo)>)field?.GetValue(ServiceProviderCache.Instance);
dict.Clear();
Is there a supported methodology to get this to work? I was thinking that if I made the DBContextOptions unique, then I wouldn't have an issue with EF reusing the existing options and not calling OnModelCreationg, but I couldn't get that to work.
I'm using EntityFrameworkCore 6.0.2 if it matters.