ASP.NET核心Entity Framework空值连接字符串

时间:2018-06-09 11:01:36

标签: c# asp.net entity-framework asp.net-core

我想将我的api连接到SQL Server数据库。我在我的启动类中获得了一个空连接字符串值。我完全不知道自己做错了什么。请你检查一下,让我知道我应该纠正什么?提前谢谢。

Startup.cs

var connectionSettings = Configuration.GetSection("Connection").Get<ConnectionSettings>();

services.AddDbContextPool<Context>(
      options => options
            .UseSqlServer(connectionSettings.ConnectionString));

我的appsettings.json连接如下:

"Connection": [
{
  "EFMode": "MSSQL",
  "DatabaseName": "Shop",
  "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=Shop;Trusted_Connection=True,MultipleActiveResultSets=True"
}

Program.cs(主要课程)中:

var db = services.GetService<Context>();

if (db != null)
{
    var cs = services.GetService<ConnectionSettings>();
    db.Database.Migrate();

    var dt = services.GetService<DefaultTriggers>();
}

我的Context.cs

var connectionSettings = config.GetSection("Connection").Get<ConnectionSettings>();

var optionsBuilder = new DbContextOptionsBuilder<Context>();
optionsBuilder.UseSqlServer(connectionSettings.ConnectionString);

return new Context(optionsBuilder.Options);

ConnectionSettings.cs

    public class ConnectionSettings
{
    public string ConnectionString { get; set; }
    public string DatabaseName { get; set; }
}

2 个答案:

答案 0 :(得分:1)

您必须更改设置才能拥有一个连接对象(请注意,我已删除了[数组]

"Connection": {
  "EFMode": "MSSQL",
  "DatabaseName": "Shop",
  "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=Shop;Trusted_Connection=True,MultipleActiveResultSets=True"
}

或者您需要指示配置对象加载ConnectionSettings

的数组
var connectionSettings = Configuration.GetSection("Connection").Get<ConnectionSettings[]>();
var shopConnection = connectionSettings.First(s => s.DatabaseName == "Shop");

答案 1 :(得分:0)

您可以简化这样的连接字符串:

var connectionString = config["Connection:ConnectionString"];