Home > Blockchain >  Unable to create an object of type '<dbcontext>'. For the different patterns support
Unable to create an object of type '<dbcontext>'. For the different patterns support

Time:11-18

I'm having an issue creating my first migration in my project which is Identity Server.

I get the following error when running add-migration initialcreate

Unable to create an object of type 'dbcontext'. For the different patterns supported at design time

Looking online, it seems I need to create a class which inherits from IDesignTimeDbContextFactory.

Below is my context:

public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>, IApplicationDbContext
    {
        public DbSet<Todos> ToDos { get; }

        public ApplicationDbContext(DbContextOptions options, IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
        {
        }

        
    }

Next is my DesignTime class:

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
            optionsBuilder.UseSqlServer("Data Source=blog.db");

            return new ApplicationDbContext(optionsBuilder.Options);
        }
    }

The issue I have is ApplicationDbContext expects two parameters, and I'm unsure how I can pass in the IOptions<OperationalStoreOptions> operationalStoreOptions

CodePudding user response:

Via dependency injection, as long as you have that configured?

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        protected IOptions<OperationalStoreOptions> _storeOptions;
        public ApplicationDbContextFactory(IOptions<OperationalStoreOptions> operationalStoreOptions)
        {
            _storeOptions = operationalStoreOptions;
        }
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
            optionsBuilder.UseSqlServer("Data Source=blog.db");

            return new ApplicationDbContext(optionsBuilder.Options, _storeOptions);
        }
    }
  • Related