简体   繁体   English

从appsettings.json获取ConnectionString

[英]Get ConnectionString from appsettings.json

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中进行配置来从appsettings.json中获取连接字符串,但该字符串不起作用,并引发错误InvalidOperationException: No database provider has been configured for this DbContext.

Startup.cs 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 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 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);
        });
    }
}

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);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM