从appsettings.json读取entity.Framework的ConnectionString

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从appsettings.json读取entity.Framework的ConnectionString相关的知识,希望对你有一定的参考价值。

我尝试从appsettings.json读取一个ConnectiongString for entityFramework和mysql,但是我收到错误:

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

这是我的appsettings.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;"
    }  
}

以上是关于从appsettings.json读取entity.Framework的ConnectionString的主要内容,如果未能解决你的问题,请参考以下文章

从 .NET Core 2 中的类中读取 appsettings.json

无法从 asp dot net 3.1 中的 appsettings.json 读取字符串数组

NET问答: 不能从 appsettings.json 中以 string[] 形式读取?

如何从 appsettings.json 文件中的对象数组中读取值

从 .net 标准库中读取 appsettings.json

您如何以与其前身 webforms 相同的风格从 appsettings.json 中读取信息?