Home > Software engineering >  constructor with dbcontextoptions not working, unable to create instance of context
constructor with dbcontextoptions not working, unable to create instance of context

Time:04-23

Just created a new dotnet web app and can't quite get to create my database.

In my Infrastructure Layer I added a dbcontext :

    public class SurveyContext : DbContext 
    {
        public SurveyContext(DbContextOptions<SurveyContext> options) : base(options)
        {
        }

        public DbSet<Survey> Surveys { get; set; }
        public DbSet<Question> Questions { get; set; }
        public DbSet<Answer> Answers { get; set; }

    }

In API, Program.cs I added this:

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<SurveyContext>(x => x.UseSqlite(connectionString));

I tried creating migrations, but I got this error

Unable to create an object of type 'SurveyContext'

To avoid a IDesignTimeDbContextFactory, I added a default constructor (public SurveyContext(){}) and ServiceLifetime.Transient in the injection, as indicated here. But now I get a different kind of error

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 object in its constructor and passes it to the base constructor for DbContext.

I never had this kind of problem before. Can someone guide me to understanding what I'm doing wrong?

CodePudding user response:

Turns out I made a mistake when installing packages. I had the EntityFrameworkCore.Design in the Infrastructure project instead of API.

  • Related