【问题标题】:Format of the initialization string does not conform to specification starting at index 0 error EF Core初始化字符串的格式不符合从索引 0 开始的规范错误 EF Core
【发布时间】:2021-10-06 20:42:04
【问题描述】:

我正在使用 .NET5 构建应用程序,并尝试使用 EF Core 更新迁移,但出现以下错误:

初始化字符串的格式不符合从索引 0 开始的规范。

通过查看类似的帖子,我发现我的connectionstring 是问题所在。但是我似乎找不到要使用的正确字符串。如果我查看我的 localDB 的属性,它会说它的 connectionstring 是:

Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

我将其设置为 DefaultConnection appsettings.json 并在 startup.cs 中像这样连接

services.AddDbContext<AppDbContext>(options => options.UseSqlServer("DefaultConnection"));

任何想法将不胜感激。

谢谢。

编辑:

先卸载SQL Express,安装后会得到这个字符串:

Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;

再次安装 localDB 后,我通过将连接字符串修改为:

Server=(localdb)\\MSSQLLocalDB;Database=master;Trusted_Connection=True;

【问题讨论】:

    标签: .net sql-server entity-framework


    【解决方案1】:

    .UseSqlServer(string) 需要一个连接字符串,而不是配置参数的名称。

    connectionString 
    String 
    The connection string of the database to connect to.
    

    因此,您必须从配置中获取连接字符串并将其传递给.UseSqlServer。例如,在 ASP.NET 中有一个带有 IConfiguration 实例的 Startup 类,您可以使用它。 EG

    services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    

    【讨论】:

    • 我已经尝试过了,但是当我这样做时,我得到了错误:值不能为空。 (参数'connectionString')
    • 那是配置问题,不是 EF 问题。
    • 有什么想法吗?我已经尝试了很多东西。如果我使用您提供的版本,我什至无法添加迁移。我可以用我的版本做到这一点
    猜你喜欢
    • 2012-01-04
    • 2015-05-01
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    相关资源
    最近更新 更多