从 appsettings.json 获取 ConnectionString

问题描述 投票:0回答:1

我关注了这篇文章,我试图通过在 Startup.cs 中配置从 appsettings.json 获取连接字符串,但它不起作用并抛出错误

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);
        });
    }
}
c# entity-framework asp.net-core
1个回答
1
投票

扩展配置方法如下:

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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.