asp.net-coreentity-framework-coreef-code-firstentity-framework-migrations

Unable to create a 'DbContext' of type ''. The exception 'Object reference not set to an instance of an object.'


I am trying to create migration using Add-Migration InitialMigrations in my Asp.net Core 8 Web API project, but I am getting the following error:

Unable to create a 'DbContext' of type 'AMSContext'. The exception 'Object reference not set to an instance of an object.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728.

I tried lots of solutions on the internet, but no solution worked for me.

AMSContext.cs

public partial class AMSContext :  BaseContext
{
    private readonly ICurrentUser _currentUser;

    public AMSContext(DbContextOptions<AMSContext> options,

        ICurrentUser currentUser

        ) : base(options)
    {
        _currentUser = currentUser;
    }
// Dbsets come here
}

BaseContext.cs

public abstract class BaseContext : IdentityDbContext<ApplicationUser, ApplicationRole, int, IdentityUserClaim<int>, IdentityUserRole<int>, IdentityUserLogin<int>, ApplicationRoleClaim, IdentityUserToken<int>>
{
    protected BaseContext(DbContextOptions options) : base(options)
    {

    }
    
}

In Program.cs

services.AddDbContext<AMSContext>(options =>
{
    options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"), o =>
    {
        o.CommandTimeout((int)TimeSpan.FromMinutes(2).TotalSeconds);
        o.MigrationsAssembly(Assembly.GetAssembly(typeofMSContext))!.FullName);
    });
    options.EnableSensitiveDataLogging();
});

Add-Migration InitialMigrations -verbose

Using project 'AMS.DATA'. Using startup project 'AMS'. Build started... Build succeeded. C:\Program Files\dotnet\dotnet.exe exec --depsfile D:\AMS\AMS\AMS\bin\Debug\net8.0\AMS.deps.json --additionalprobingpath C:\Users\Dell\.nuget\packages --additionalprobingpath "C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages" --runtimeconfig D:\AMS\AMS\AMS\bin\Debug\net8.0\AMS.runtimeconfig.json C:\Users\Dell\.nuget\packages\microsoft.entityframeworkcore.tools\8.0.3\tools\netcoreapp2.0\any\ef.dll migrations add InitialMigrations --json --verbose --no-color --prefix-output --assembly D:\AMS\AMS\AMS\bin\Debug\net8.0\AMS.DATA.dll --project D:\AMS\AMS\AMS.Data\AMS.DATA.csproj --startup-assembly D:\AMS\AMS\AMS\bin\Debug\net8.0\AMS.dll --startup-project D:\AMS\AMS\AMS\AMS.csproj --project-dir D:\AMS\AMS\AMS.Data\ --language C# --configuration Debug --working-dir D:\AMS\AMS --root-namespace AMS.DATA --nullable Using assembly 'AMS.DATA'. Using startup assembly 'AMS'. Using application base 'D:\AMS\AMS\AMS\bin\Debug\net8.0'. Using working directory 'D:\AMS\AMS\AMS'. Using root namespace 'AMS.DATA'. Using project directory 'D:\AMS\AMS\AMS.Data\'. Remaining arguments: . Finding DbContext classes... Finding IDesignTimeDbContextFactory implementations... Finding application service provider in assembly 'AMS'... Finding Microsoft.Extensions.Hosting service provider... Using environment 'Develpoment'. Using application service provider from Microsoft.Extensions.Hosting. Found DbContext 'AMSContext'. Finding DbContext classes in the project... Using context 'AMSContext'. Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create a 'DbContext' of type ''. The exception 'Object reference not set to an instance of an object.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 ---> System.NullReferenceException: Object reference not set to an instance of an object.

    at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindCollectionMapping(RelationalTypeMappingInfo info, Type modelType, Type providerType, CoreTypeMapping elementMapping)
    at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.\<\>c.\<FindMappingWithConversion\>b__8_0(ValueTuple\`4 k, RelationalTypeMappingSource self)
    at System.Collections.Concurrent.ConcurrentDictionary\`2.GetOrAdd\[TArg\](TKey key, Func\`3 valueFactory, TArg factoryArgument)
    at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMappingWithConversion(RelationalTypeMappingInfo mappingInfo, Type providerClrType, ValueConverter customConverter)
    at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMappingWithConversion(RelationalTypeMappingInfo mappingInfo, IReadOnlyList\`1 principals)
    at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMapping(IProperty property)
    at Microsoft.EntityFrameworkCore.Metadata.Conventions.ElementMappingConvention.\<ProcessModelFinalizing\>g__Validate|4_0(IConventionTypeBase typeBase)
    at Microsoft.EntityFrameworkCore.Metadata.Conventions.ElementMappingConvention.ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext\`1 context)
    at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelFinalizing(IConventionModelBuilder modelBuilder)
    at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelFinalizing(IConventionModelBuilder modelBuilder)
    at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel()
    at Microsoft.EntityFrameworkCore.Infrastructure.ModelRuntimeInitializer.Initialize(IModel model, Boolean designTime, IDiagnosticsLogger\`1 validationLogger)
    at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, ModelCreationDependencies modelCreationDependencies, Boolean designTime)
    at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel(Boolean designTime)
    at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
    at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.\<\>c.\<TryAddCoreServices\>b__8_4(IServiceProvider p)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor\`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.\<\>c__DisplayClass2_0.\<RealizeService\>b__0(ServiceProviderEngineScope scope)
    at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(ServiceIdentifier serviceIdentifier, ServiceProviderEngineScope serviceProviderEngineScope)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService\[T\](IServiceProvider provider)
    at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
    at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
    at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
    at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure\<System.IServiceProvider\>.get_Instance()
    at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService(IInfrastructure\`1 accessor, Type serviceType)
    at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService\[TService\](IInfrastructure\`1 accessor)
    at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService\[TService\](IInfrastructure\`1 accessor)
    at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)    --- End of inner exception stack trace ---
    at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
    at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.\<\>c__DisplayClass0_0.\<.ctor\>b__0()
    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.\<\>c__DisplayClass3_0\`1.\<Execute\>b__0()
    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) Unable to create a 'DbContext' of type ''. The exception 'Object reference not set to an instance of an object.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Solution

  • After an extensive debugging process and thorough examination of the error call trace, I successfully identified the issue. It was related to two fields, as depicted in the provided configuration screenshot. Initially defined as datetime in the model class configuration

    I have changed later these fields to int in my model class but forget to change their type in Dbcontext model configuration. After changing type from datetime2 to int the issue was finally resolved in DbContext according to model.