首页 > 解决方案 > 如何解决此连接字符串错误?

问题描述

我有一个 .net 核心应用程序,我正在尝试与 EntityFrameworkCore 一起使用来构建数据库,但是当我这样做时:

update-database

出现此错误:

Format of the initialization string does not conform to specification starting at index 0.

我已将连接字符串更改为标准格式并尝试了此操作,因为我有一个错误,因为我的主项目的程序集与我用于类的库不同:

services.AddDbContext<conn>(options => options.UseSqlServer("connname", b => b.MigrationsAssembly("conn")));


"ConnectionStrings": {
"FITMEConnection": "Server=foo;Database=fooname;Trusted_Connection=True"
},

我对此感到很生气,因为我已经搜索了这个错误并且似乎很容易解决。我究竟做错了什么?谢谢你。

标签: .net-coreentity-framework-core

解决方案


首先,您的appsettings.json文件应如下所示:

{
  "ConnectionStrings": {
    "FITMEConnection": "Server=foo;Database=foo;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

然后执行以下操作:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        var connectionString = Configuration.GetConnectionString("FITMEConnection"); // <-- Look at here

        services.AddDbContext<YourDbContext>(options => options.UseSqlServer(connectionString),b => b.MigrationsAssembly("MigrationAssemblyName")); 
   }
}

现在它应该工作了!


推荐阅读