【问题标题】:How to use connection string from appsettings.json on DAL layer project如何在 DAL 层项目中使用 appsettings.json 中的连接字符串
【发布时间】:2019-02-15 20:03:04
【问题描述】:

在 vs.net 中,我在一个解决方案中有多个项目,webApplication 是启动项目(asp.net core 2.1)和 DataAccess 项目(类库 .net 框架 4.6),我从 app.config(DataAccess 项目)复制了连接字符串到 webApplication 中的 appsettings.json 但在访问数据库时发生错误: 在应用程序配置文件中找不到名为“Hemmat_Entities”的连接字符串。

DAL 项目中的 app.config:

 <connectionStrings>
      <add name="Hemmat_Entities" connectionString="metadata..."
 </connectionStrings> 

asp.net core 中的appsettings 是:

{
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "Hemmat_Entities": "data source=.;initial 
           catalog=hemmat_new;integrated 
             security=True;multipleactiveresultsets=True;application 
             name=EntityFramework&quot;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

【问题讨论】:

  • 你能展示你用来读取连接字符串的代码吗?
  • 没有代码用于读取连接字符串,只是我将它添加到appsettings.json,DataAccess层从app.config读取连接字符串并且它工作正常,但是当从webApp项目访问时它给出了错误: 找不到名为“Hemmat_Entities”的连接字符串
  • 你需要在 web.config 中为 asp.net 核心项目中的 DAL 的 connectionString 条目(不是它附带一个,但你可以有一个)或将 DAL 更新为 .net 核心跨度>
  • 你的意思是把 web.config 添加到 asp.net core 项目中?怎么能做到这一点?只是从新项目复制或添加?

标签: c# asp.net-core web-config


【解决方案1】:

我找到了解决办法,我的错误是Asp.net core 2项目针对.net core,改成.net framework后,问题解决了!

所以如果我们想引用在.net461下运行的其他项目,在我的例子中,主项目asp.net core 2必须处于.net框架目标模式。

【讨论】:

    【解决方案2】:

    尝试使用 GetValue 获取 Hemmat_Entities 的值。嵌套值需要:

    string connectionString = Configuration.GetValue&lt;string("ConnectionStrings:Hemmat_Entities");

    【讨论】:

    • 在 Asp.net Core 中获取值并不能解决我的问题,DAL 层无法访问连接字符串。
    【解决方案3】:

    @t-prisar。 您需要通过表示层注入一个,传递给 DAL 构造函数。

    【讨论】:

      猜你喜欢
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2019-08-05
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多