0

I followed this article and I tried to get the connectionstring from appsettings.json by configuring in Startup.cs but it is not working and throws the error InvalidOperationException: No database provider has been configured for this DbContext.

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContext<StudentManagementContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("StudentDatabase")));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "StudentDatabase": "Data Source=localhost;Initial Catalog=StudentManagement;persist security info=True;user id=sa;password=test@123"
  }
}

StudentManagementContext.cs

public partial class StudentManagementContext : DbContext
{
    public StudentManagementContext()
    {
    }

    public StudentManagementContext(DbContextOptions<StudentManagementContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Student> Student { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
        //optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=StudentManagement;persist security info=True;user id=sa;password=test@123");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasAnnotation("ProductVersion", "2.2.6-servicing-10079");

        modelBuilder.Entity<Student>(entity =>
        {
            entity.Property(e => e.StudentName)
                .IsRequired()
                .HasMaxLength(100);
        });
    }
}
Gopi
  • 5,656
  • 22
  • 80
  • 146
  • refer this : https://stackoverflow.com/questions/45796776/get-connectionstring-from-appsettings-json-instead-of-being-hardcoded-in-net-co – Kalpesh Boghara Jul 12 '19 at 05:22
  • @KalpeshBoghara Thanks. I referred it even earlier but would like to know why this fails. – Gopi Jul 12 '19 at 05:41
  • Why is there a parameterless constructor, are you sure the right constructor is called? Try removing that constructor and the `OnConfiguring` override since you are not using that. – bartbje Jul 12 '19 at 07:57

1 Answers1

1

Extend the configuration method as below:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json")
               .Build();
            var connectionString = configuration.GetConnectionString("StudentDatabase");
            optionsBuilder.UseSqlServer(connectionString);
        }
    }
NetDev
  • 107
  • 8