Skip to main content
 首页 » 编程设计

c#之在应用程序设置中添加 Entity Framework 连接字符串作为变量

2024年02月06日20jpfss

我的 app.config 文件中有这个自动生成的连接字符串。这是通过在 Entity Framework 中创建数据库优先模型生成的:

<add name="HalloweenContext" connectionString="metadata=res://*/HalloweenDbModel.csdl| 
                                                    res://*/HalloweenDbModel.ssdl| 
                                                    res://*/HalloweenDbModel.msl; 
                         provider=System.Data.SqlClient; 
                         provider connection string=&quot; 
                         data source=localhost\sqlexpress; 
                         initial catalog=Halloween; 
                         integrated security=True; 
                         MultipleActiveResultSets=True; 
                         App=EntityFramework&quot;" 
 providerName="System.Data.EntityClient" /> 

我被指示获取该连接字符串并将其放入应用程序设置中(图片用于说明应用程序设置页面):

我已将这部分内容剪切/粘贴到名为“HalloweenContext”的设置变量中,并将 &quote; 更改为单引号:

"metadata=res://*/HalloweenDbModel.csdl| 
          res://*/HalloweenDbModel.ssdl| 
          res://*/HalloweenDbModel.msl; 
          provider=System.Data.SqlClient; 
          provider connection string='; 
          data source=localhost\sqlexpress; 
          initial catalog=Halloween; 
          integrated security=True; 
          MultipleActiveResultSets=True; 
          App=EntityFramework';" 
 providerName="System.Data.EntityClient" 

但是,当我将上述选择粘贴到 HallowContext 的应用程序设置变量中时,我收到以下错误消息:

我检查了连接字符串并重新检查了它,但我无法弄清楚它有什么问题。我删除了引号、添加了引号等,但似乎对我没有任何作用。

我想知道,也许,因为这是一个 EF 连接字符串,我是否将它错误地放入了应用程序设置中?

更新:使用下面答案中概述的新数据连接字符串后,我现在收到一个新错误:

The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection...

因此,我认为我可能无法使用此上下文代替我的 db-first 上下文。但是,我似乎也无法按原样使用我的 db-first 上下文,所以我处于停顿状态。我会继续寻找解决方案,非常感谢迄今为止提供的帮助。

作为补充说明,我要重申原始连接字符串工作正常并且在 app.config 文件中。但是,我被指示将其添加到应用程序设置中。就我个人而言,我觉得如果它在 app.config 文件中有效,那么这应该就足够了,但是我们已经被指示通过将连接字符串添加到应用程序设置并像 connectionString = Settings 一样使用它来使用它。默认.HaloweenContext。最终目标是在我们可以使用的应用程序设置中设置许多连接字符串。

旁注:我相信在 app.config 文件中使用多个命名连接字符串是可行的方法。将这些连接字符串添加为应用程序设置而不是手动将它们添加到 app.config 文件有什么好处吗?

请您参考如下方法:

那不是 ADO.NET 连接字符串,看起来像 EF 字符串

这是你想要的conn字符串:

"data source=localhost\sqlexpress; initial catalog=Halloween; integrated security=True;MultipleActiveResultSets=True;"