数据库优先 EF 和 ASP.NET Core 3 Web API 在 Azure 上发布,连接字符串错误

Database first EF and ASP.NET Core 3 Web API published on Azure, connection string error

我正在开发一个 ASP.NET Core 3 Web API,其中包含数据库首先生成的数据库上下文。 我在 appsettings.json 文件中有连接字符串。

当我在 IIS Express 本地 运行 时一切正常。

问题是当我在 Azure 上发布它时,出现错误:

System.ArgumentException: Keyword not supported: 'data source'.
[...]

我注意到连接字符串在发布时更改为:

metadata=res://*/DTOs.csdl|res://*/DTOs.ssdl|res://*/DTOs.msl;provider=System.Data.SqlClient;provider connection string='data source=*****;initial catalog=*****;persist security info=True;user id=*****;password=*****;MultipleActiveResultSets=True;App=EntityFramework'",

至:

metadata=res://*/DTOs.csdl|res://*/DTOs.ssdl|res://*/DTOs.msl;provider=System.Data.SqlClient;provider connection string="data source=*****;initial catalog=*****;persist security info=True;user id=*****;password=*****;MultipleActiveResultSets=True;App=EntityFramework""

作为解决方法,我更改了行

services.AddScoped<palmdtos>(_ => new MyDbContext(Configuration.GetConnectionString("myConnectionString")));

services.AddScoped<palmdtos>(_ => new MyDbContext(Configuration.GetConnectionString("myConnectionString").Replace("&quot;","'").Replace("&amp;", "&")));

有更好的方法吗?

你能尝试更新设置吗?

在 Azure 面板中:

Select App -> Application Settings -> Enter new Connection String -> Save

Models created with the EF Designer are different from Code First in that your model already exists and is not generated from code when the application runs. The model typically exists as an EDMX file in your project.

The designer will add an EF connection string to your app.config or web.config file. This connection string is special in that it contains information about how to find the information in your EDMX file.

参考这个article.

原因是我们使用的其中一个 EDMX 文件的连接字符串。由于 EDMX 必须是只读的,我们不得不在 Azure 中使用不同的连接字符串。

替换时&quote;通过单引号 ',它将再次正常工作。所以去 azure 网站 > Configuration > Connection strings > 添加你的 conn 字符串 custom 类型。

注意:确保你的 Entity Framework 连接字符串也是 select Custom 而不是 SQLAzure,即使数据库在 Azure 上运行。