在ASP.NET程序的多层开发中,我们常将数据访问层写在一个Class Library中。当在Class Library中使用了connection string时,很多人就发现了问题,因为Class Library最终给别人的是一个DLL,并不包含我们常见的web.config或app.config。这样的话,当我们使用的数据库需要变动时,我们就不能简单的通过修改web.config或app.config来改变connection string。

不知道大家是怎么去解决这个问题的(可以share一下:)),我是这样来解决的:

1) 在建立了Class Library后,connection string会被放在app.config文件中,如:


     <add name="TestProj.Properties.Settings.testConnectionString"
          connectionString
="Data Source=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True"
          providerName
="System.Data.SqlClient" />
</connectionStrings>


2) 在我们的ASP.NET程序中,如果需要替换这个DLL中的connection string,我们可以在web.config中覆盖这个connection string(一定要是相同的名字),这样的话就可以达到替换的目的。如:


    <add name="TestProj.Properties.Settings.testConnectionString"
            connectionString
="Data Source=.\SQLEXPRESS;Initial Catalog=test222;Integrated Security=True"
            providerName
="System.Data.SqlClient" />
  
</connectionStrings>

 

此时,DLL将会使用新的database test222。问题不算太大,但是非常的实用。希望对大家有所帮助!

Have a nice day!

相关文章:

  • 2021-07-25
  • 2022-12-23
  • 2022-02-09
  • 2022-12-23
  • 2021-05-11
  • 2021-07-20
猜你喜欢
  • 2022-12-23
  • 2022-02-09
  • 2022-12-23
  • 2021-11-25
  • 2021-10-29
  • 2021-09-12
相关资源
相似解决方案