gpt4 book ai didi

c# - EF Core2.2 : Scaffold-DbContext not working with named connection string in WPF project

转载 作者:行者123 更新时间:2023-11-30 12:19:30 28 4
gpt4 key购买 nike

我想在我的 .net Framework 4.7 项目中首先使用 EF Core 2.2 和数据库。运行此命令可以正常工作:

Scaffold-DbContext "data source=dbServer;initial catalog=myData;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Database

但是随后 MS 发出了这个警告:

warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.

所以我想我按照说明做了,并按如下方式更新了脚本:

Scaffold-DbContext "name=MyConnection" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Database

导致此错误的原因:

A named connection string was used, but the name 'MyConnection' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See https://go.microsoft.com/fwlink/?linkid=850912 for more information.

命名连接本身工作正常,我已经通过注释掉由 EF 核心生成的第一行并使用第二行来测试它:

//optionsBuilder.UseSqlServer("data source=dbServer;initial catalog=myData;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework");
optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);

启动程序,它可以连接并按预期显示数据。但我更愿意在 Scaffold-DbContext 中设置 alrady。有什么想法吗?

为了完整起见,这里是 app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="data source=dbServer;initial catalog=myData;integrated security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
...

最佳答案

EF Core2.2: Scaffold-DbContext not working with named connection string in WPF project

事实。两种错误信息

Note that named connection strings are only supported when using IConfiguration and a service provider, such as in a typical ASP.NET Core application.

Scaffold-DbContext -Connection 参数的命令文档

...For ASP.NET Core 2.x projects, the value can be name=<name of connection string>. In that case the name comes from the configuration sources that are set up for the project...

指出命名连接字符串不能与基于“遗留”app.config (NET Framework) 的项目中的 Scaffold-DbContext 命令一起使用。

因此,对于 Scaffold-DbContext,您必须使用实际的连接字符串。并在这里命名连接字符串(我猜是警告):

optionsBuilder.UseSqlServer(
ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);

关于c# - EF Core2.2 : Scaffold-DbContext not working with named connection string in WPF project,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57710607/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com