I recently upgraded my app to .net core 6 and now I am getting this error on this.ChangeTracker in my code:
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
_options = options;
this.ChangeTracker.LazyLoadingEnabled = false;
this.ChangeTracker.AutoDetectChangesEnabled = true;
}
Before erroring it was performing dependency injection
IUnityContainer container = HangfireUnityConfig.GetConfiguredContainer();
var userService = container.Resolve<IUserService>();
This is the line of code where I AddDBContext with the connection string.
var connectionString = builder.Configuration.GetConnectionString("ConnectionString");
builder.Services.AddDbContext<ApplicationDbContext>(x => x.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
Full error message: System.InvalidOperationException
HResult=0x80131509
Message=No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
Source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, DbContextOptions contextOptions, DbContext context)
at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
at Microsoft.EntityFrameworkCore.DbContext.get_ChangeTracker()
at MyApp.Data.ApplicationDbContext..ctor(DbContextOptions`1 options) in C:\MyApp\Data\ApplicationDbContext.cs:line 34
Any ideas how to solve this?
Update
I added the OnConfiguring() method to my ApplicationDbContext and now get a new error when trying to cast to IObjectContextAdapter.
The error says System.InvalidCastException: Unable to cast object of type 'MyApp.Data.ApplicationDbContext' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'.
This is the code it breaks on
public List<KeyValuePair<string, long>> GetKeys(EntityEntry entry)
{
var keys = new List<KeyValuePair<string, long>>();
var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
if (objectStateEntry.EntityKey.EntityKeyValues != null)
{
keys.AddRange(objectStateEntry.EntityKey.EntityKeyValues.Select(key => new KeyValuePair<string, long>(key.Key, Convert.ToInt64(key.Value))));
}
return keys;
}
This is what my OnConfiguring() method looks like
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("myconnectionstring");
}
}