从appsettings.json获取ConnectionString [英] Get ConnectionString from appsettings.json

查看:467
本文介绍了从appsettings.json获取ConnectionString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我关注了这篇文章,然后我尝试通过在Startup.cs中进行配置从appsettings.json获取连接字符串,但它无法正常工作,并引发错误 InvalidOperationException:没有为此DbContext配置数据库提供程序。

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


推荐答案

扩展配置方法如下:

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

这篇关于从appsettings.json获取ConnectionString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆