簡體   English   中英

從appsettings.json中讀取ConnectionString以獲取Entity.Framework

[英]read ConnectionString from appsettings.json for entity.Framework

我嘗試從appsettings.json中讀取用於實體框架和MySQL的ConnectiongString,但出現錯誤:

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

這是我的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;"
    }
  }
}

這是我的創業公司:

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

這是我的DBContext:

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

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

如果我將“ MigrationConnection”更改為:

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

會是什么呢?

您收到錯誤消息是因為Configuration.GetConnectionString("MigrationConnection")返回null 它應該替換為:

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

或者,您可以將appsettings.json的結構更改為:

{
    "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;"
    }  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM