繁体   English   中英

EF Core2.2:Scaffold-DbContext无法在WPF项目中使用命名连接字符串

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

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

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

但随后MS发出警告:

警告要保护连接字符串中可能存在的敏感信息,应将其移出源代码。 有关存储连接字符串的指导,请参阅http://go.microsoft.com/fwlink/?LinkId=723263

所以我认为我按照说明执行并更新脚本如下:

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

这会导致此错误:

使用了命名连接字符串,但在应用程序的配置中找不到名称“MyConnection”。 请注意,只有在使用“IConfiguration”和服务提供程序时才支持命名连接字符串,例如在典型的ASP.NET Core应用程序中。 有关详细信息,请参阅https://go.microsoft.com/fwlink/?linkid=850912

命名连接本身工作正常,我已经通过命令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无法在WPF项目中使用命名连接字符串

事实。 这两个错误消息

请注意,只有在使用IConfiguration和服务提供程序时才支持命名连接字符串,例如在典型的ASP.NET Core应用程序中。

脚手架的DbContext用于命令文档-Connection参数

...对于ASP.NET Core 2.x项目,值可以是name = <连接字符串的名称> 在这种情况下,名称来自为项目设置的配置源...

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM