ASP.NET CORE: IConfiguration can not access ConnectionString inside Class Library

110 views Asked by At

I have a class library for a Repository to handle the Database operation, and I tried to create DbContext and set ConnectionString as well, but it did not work.

    namespace CoreCrud.Repository
    {
        public class CoreCrudDBContext: DbContext
        {
            private readonly IConfiguration _configuration;
            public CoreCrudDBContext(DbContextOptions<CoreCrudDBContext> options, IConfiguration configuration) : base(options)
            {
                _configuration = configuration;
            }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                String connString = _configuration.GetConnectionString("CoreCrudDatabase");
                Console.WriteLine(connString);
    
                if (!optionsBuilder.IsConfigured)
                    optionsBuilder.UseMySQL(connString);
            }
    
            public DbSet<Person> person { get; set; }
        }
    }

I also have appsettings.json:


    {
      "ConnectionStrings": {
        "CoreCrudDatabase": "server=localhost;database=core_crud;user=root;password=password"
      }
    }

And the DbContext is defined in Startup.cs in web mvc project as follows:


    public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllersWithViews();
                services.AddDbContext<CoreCrudDBContext>();
            }

But each time the project runs it gives this error: optionsBuilder.UseMySQL(connString); inside OnConfiguring method.

System.ArgumentNullException: 'Value cannot be null. (Parameter 'connectionString')'

0

There are 0 answers