多專案的ConnectionStrings管理(asp.net)

  • 65
  • 0
  • 2023-09-19

在獨立的project執行另一個project產生的dll檔, 出現No connection string named 'MyXXX' could be found in the application config file.

ConnectionStrings設定檔需在執行/設為startup project裡的app.config/web.config ,若連線DB的是另外project產生的, 執行project裡也要有一份設定

參考文章 https://stackoverflow.com/questions/12622408/no-connection-string-named-myentities-could-be-found-in-the-application-config

可在方案檔下統一個config, 其他project做file link的方式, 放到執行環境裡
1.sln檔目錄新增ConnectionStrings.config

<connectionStrings>
	<add name = "DEV"
	connectionString = "Data Source=NBT\SQLEXPRESS;
						Initial Catalog=DEV;Integrated Security=True;"
	providerName = "System.Data.SqlClient"/>
</connectionStrings>
2-1.需引用的project config設定, 原設定改指到ConnectionStrings.config
<configuration>
	...
	<connectionStrings configSource="ConnectionStrings.config" />
	...
</configuration>

2-2.project上按右鍵add existing item, 新增sln檔目錄下的
	ConnectionStrings.config file link, 並設定copy always
3. 執行目標project, 確定ConnectionStrings.config
	及web.config或app.config有copy到執行環境

參考文章 https://salimbenhadou.wordpress.com/2016/11/06/centralize-and-share-connection-strings-among-multiple-projects/