read ConnectionString from appsettings.json for entity.Framework

浪子不回头ぞ 提交于 2019-12-08 07:32:50

问题


i try to read a ConnectiongString from appsettings.json for entityFramework and MySQL, but i get the error:

System.ArgumentNullException: Value cannot be null.
Parameter name: connectionString

this is my appsetings.json:

{
  "Data": {
    "ConnectionStrings": {
      "DefaultConnection": "server=database;userid=hawai;pwd=mysecret;port=3306;database=identity;sslmode=none;",
      "MigrationConnection": "server=127.0.0.1;userid=hawai;pwd=mysecret;port=3306;database=identity;sslmode=none;"
    }
  }
}

this is my Startup:

    public class Startup
        {
            public IConfiguration Configuration { get; set; }

            public Startup(IHostingEnvironment env)
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddEnvironmentVariables();
                Configuration = builder.Build();

            }

            public void ConfigureServices(IServiceCollection services)
            {


                    var connection = Configuration.GetConnectionString("MigrationConnection");
                    services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MigrationConnection")));


                services.AddMvc();
}

and this is my DBContext:

public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> dbContextOptions) :
            base(dbContextOptions)
        {

        }
        public DbSet<Person> People { get; set; }
    }

if i change the "MigrationConnection" with:

server=127.0.0.1;userid=xxx;pwd=xxx;port=3306;database=xxx;sslmode=none;

what could it be?


回答1:


You're getting the error because Configuration.GetConnectionString("MigrationConnection") returns null. It should be replaced with:

var connection = Configuration.GetSection("Data").GetConnectionString("MigrationConnection");

Or you can change the structure of appsettings.json to:

{
    "ConnectionStrings": {
      "DefaultConnection": "server=database;userid=hawai;pwd=mysecret;port=3306;database=identity;sslmode=none;",
      "MigrationConnection": "server=127.0.0.1;userid=hawai;pwd=mysecret;port=3306;database=identity;sslmode=none;"
    }  
}


来源:https://stackoverflow.com/questions/51306119/read-connectionstring-from-appsettings-json-for-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!