0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

.NET Core MVCでDB接続ができなくて困った話。

Posted at

.NET Core MVCでDB接続ができなくて困った話。

困った経緯

.NET Core MVCを使ってのWebアプリを製造中に起きました。
DBの内容を表示させようとWeb.config,ソースを下記のように記載し
デバッグを行うとエラーが発生しました。
調べて出てきたソースと同じように書いているのに接続できず1週間ぐらい困っていました。

Web.config

<configuration>
  <connectionStrings>
    <add name="接続文字列"
         connectionString="Data Source=サーバー名;Persist Security Info=True;User ID=ユーザー名;Password=パスワード"/>
  </connectionStrings>
</configuration>

ソース

//接続文字列の取得
var connStr ConfigurationManager.ConnectionStrings["接続文字列"].ConnectionString;
var conn = new SqlConnection(connStr);
//DBへの接続
conn.Open();

解決策

Web.configは使わず、appsettings.jsonに接続文字列を記載しこっちを使うと接続できました。
appsettings.json,ソースは下記のような感じです。

appsettings.json

"接続文字列": "Data Source=サーバー名;Persist Security Info=True;User ID=ユーザー名;Password=パスワード"

ソース

       var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false);
            var configuration = builder.Build();
            IDbConnection connection = new SqlConnection(configuration.GetValue("接続文字列", ""));
            // データベースの接続開始
            connection.Open();

感想

無事DB接続ができてよかったでした。
Web.configで接続できなかった原因はいまだに不明です。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?