【问题标题】:Modifying connection string of an ASP.NET GridView -> BLL -> DAL at runtime在运行时修改 ASP.NET GridView -> BLL -> DAL 的连接字符串
【发布时间】:2012-01-18 21:35:58
【问题描述】:

我正在构建一个页面来显示带有分页的客户端数据的 GridView。我的 aspx 页面有一个 GridView,其 DataSourceID 设置为 ObjectDataSource。 ObjectDataSource 绑定到 BLL,而 BLL 又通过 DAL 访问数据。在指向静态数据库的同时,我已经启动并运行了整个过程。但是,每个客户的数据都存储在自己的数据库中。下一步是根据客户端登录修改DAL的ConnectionString。

我已将 DAL TableAdapter 配置为选项 ConnectionModifier 设置为“公共”。我的 BLL 可以修改 DAL 的连接字符串,但是我不知道如何将客户端数据库名称传递给 BLL。

public class PDFDocumentsBLL {
  private PDFTableAdapter _pdfdocumentsadapter = null;
  protected PDFTableAdapter Adapter {
    get {
      if ( _pdfdocumentsadapter == null ) {
        _pdfdocumentsadapter = new PDFTableAdapter();
        _pdfdocumentsadapter.Connection = new System.Data.SqlClient.SqlConnection(
          ConfigurationManager.ConnectionStrings["template"].ConnectionString.Replace( "TEMPLATE", "TESTCLIENT" )
          );
      }
      return _pdfdocumentsadapter;
    }
  }
  ...
}

我想用一个变量替换上面代码中的字符串“TESTCLIENT”,但是我不知道如何将这个信息传递给 BLL。

【问题讨论】:

    标签: c# pagination connection objectdatasource


    【解决方案1】:

    您可以创建某种数据库名称提供程序,它将根据用户名返回数据库名称,例如

    public class DataBaseNameProvider
    {
       public string GetDataBaseName()
       {
          var userName = Membership.GetUser().UserName;
          return GetDatabaseNameByUserName(userName);
       }
    }
    

    然后从你的 BLL 中调用那个类。

    如果你不喜欢在你的 BLL 中使用 ASP.NET 的东西,因为你不想添加额外的依赖,你仍然可以在你的 BLL 周围创建一个包装器,它可以识别成员身份并创建你的 BLL 传递那里的用户名。

    【讨论】:

      【解决方案2】:

      如果您使用的是 Windows 身份验证,那么您可以简单地使用

      ConfigurationManager.ConnectionStrings[WindowsIdentity.GetCurrent().Name]
      

      为每个用户检索整个连接字符串可能是一种很好的做法,它使其更加灵活,因此如果需要,您可以使用完全不同类型的数据库。

      【讨论】:

      • 这需要为每个客户端添加一个 Web.config 条目,而不是最易于管理的解决方案。
      【解决方案3】:

      我最终做的是向我的 BLL 添加一个 PDFDB 属性:

      public class PDFDocumentsBLL {
        private PDFTableAdapter _pdfdocumentsadapter = null;
        public string PDFDB = "PDF_TEMPLATE";
        protected PDFTableAdapter Adapter {
          get {
            if ( _pdfdocumentsadapter == null ) {
              _pdfdocumentsadapter = new PDFTableAdapter();
      
              _pdfdocumentsadapter.Connection = new System.Data.SqlClient.SqlConnection(
                ConfigurationManager.ConnectionStrings["pdf"].ConnectionString.Replace( "PDF_TEMPLATE", PDFDB )
                );
            }
            return _pdfdocumentsadapter;
          }
        }
      }
      

      然后我修改了 GetBy/FillBy 函数以将 DB 作为附加参数,并将 ObjectDataSource 配置为从 Session 变量中传递该值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-23
        • 2017-11-17
        • 2019-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-24
        • 1970-01-01
        相关资源
        最近更新 更多