2011-04-27 1 views
0

Я объединяю два моих проекта, которые могут совместно использовать одни и те же классы в одном решении с двумя веб-приложениями и библиотекой общих классов.ConnectionString в библиотеке классов

Я буквально просто сбросил все классы в проект библиотеки классов, и, как и ожидалось, у меня есть тонна ошибок для исправления. Моя главная проблема на данный момент - строка подключения. В настоящее время я это (что, очевидно, не будет работать):

''' <summary> 
    ''' Initialise the data access layer by loading the database connection string from the Web.Config file 
    ''' </summary> 
    ''' <remarks></remarks> 
    Shared Sub New() 

     _connectionString = WebConfigurationManager.ConnectionStrings("ClientFamilyManagementConnectionString").ConnectionString 

    End 

Что мне делать с моими строками подключения теперь классы не в веб-приложении?

Я действительно чувствую, что у меня что-то отсутствует, поэтому ниже я включаю пример класса из BLL и DAL. Я не могу передать строку соединения конструктору DAL - он говорит, что у него не может быть никаких параметров.

BLL:

Imports Microsoft.VisualBasic 
Imports System.Collections.Generic 

Namespace CompanyName 

<Serializable()> Public Class SubMarketSector 

    Private _id As Integer 
    Private _name As String 

    Public Property ID() As Integer 
     Get 
      Return _id 
     End Get 
     Set(ByVal value As Integer) 
      _id = value 
     End Set 
    End Property 

    Public Property Name() As String 
     Get 
      Return _name 
     End Get 
     Set(ByVal value As String) 
      _name = value 
     End Set 
    End Property 

    Public Sub New() 

    End Sub 

    Public Shared Function GetAllSubMarketSectors() As List(Of CompanyName.SubMarketSector) 

     Dim newSubMarketSectorDAO As New SubMarketSectorDAO 
     Return newSubMarketSectorDAO.GetAllSubMarketSectors 

    End Function 

    Public Shared Function GetSubMarketSectorByID(ByVal subMarketSectorID As Integer) As CompanyName.SubMarketSector 

     Dim newSubMarketSectorDAO As New SubMarketSectorDAO 
     Return newSubMarketSectorDAO.GetSubMarketSectorByID(subMarketSectorID) 

    End Function 


End Class 

End Namespace 

DAL:

Namespace CompanyName 

Public Class SubMarketSectorDAO 

    Private Const MainSelectByStatement As String = "SELECT ID, Name FROM Sub_Market_Sectors" 
    Private Const MainOrderByStatement As String = " ORDER BY Name" 

    Private Shared ReadOnly _connectionString As String = String.Empty 

    ''' <summary> 
    ''' Initialise the data access layer by loading the database connection string from the Web.Config file 
    ''' </summary> 
    ''' <remarks></remarks> 
    Shared Sub New() 

     _connectionString = WebConfigurationManager.ConnectionStrings("PursuitsConnectionString").ConnectionString 

    End Sub 

    ''' <summary> 
    ''' Returns a List of all Sub Market Sectors 
    ''' </summary> 
    ''' <returns></returns> 
    ''' <remarks></remarks> 
    Public Function GetAllSubMarketSectors() As List(Of CompanyName.SubMarketSector) 

     ' Create the Connection 
     Dim currentConnection As SqlConnection = New SqlConnection(_connectionString) 

     ' Create the Command Object, set the CommandText, add any required Parameters and set the Connection 
     Dim currentCommand As New SqlCommand 
     currentCommand.CommandText = MainSelectByStatement & MainOrderByStatement 
     currentCommand.Connection = currentConnection 

     Dim listOfSubMarketSectors As New List(Of CompanyName.SubMarketSector) 

     Using currentConnection 

      ' Open the Connection 
      currentConnection.Open() 

      ' Create the DataReader and Execute the Command 
      Dim currentDataReader As SqlDataReader = currentCommand.ExecuteReader() 

      ' Populate the list with data 
      Do While currentDataReader.Read 

       Dim newSubMarketSector As CompanyName.SubMarketSector = PopulateSubMarketSector(currentDataReader) 

       listOfSubMarketSectors.Add(newSubMarketSector) 

      Loop 

     End Using 

     Return listOfSubMarketSectors 

    End Function 

    ''' <summary> 
    ''' Return a single Sub Market Sector 
    ''' </summary> 
    ''' <returns></returns> 
    ''' <remarks></remarks> 
    Public Function GetSubMarketSectorByID(ByVal subMarketSectorID As Integer) As CompanyName.SubMarketSector 

     ' Create the Connection 
     Dim currentConnection As SqlConnection = New SqlConnection(_connectionString) 

     ' Create the Command Object, set the CommandText, add any required Parameters and set the Connection 
     Dim currentCommand As New SqlCommand 
     currentCommand.CommandText = MainSelectByStatement & " WHERE ID = @subMarketSectorID" & MainOrderByStatement 
     currentCommand.Parameters.AddWithValue("@subMarketSectorID", subMarketSectorID) 
     currentCommand.Connection = currentConnection 

     Dim newSubMarketSector As New CompanyName.SubMarketSector 

     Using currentConnection 

      ' Open the Connection 
      currentConnection.Open() 

      ' Create the DataReader and Execute the Command 
      Dim currentDataReader As SqlDataReader = currentCommand.ExecuteReader() 

      ' Populate the Market Sector 
      Do While currentDataReader.Read 

       newSubMarketSector = PopulateSubMarketSector(currentDataReader) 

      Loop 

     End Using 

     Return newSubMarketSector 

    End Function 

    Private Function PopulateSubMarketSector(ByVal currentDataReader As SqlDataReader) As CompanyName.SubMarketSector 

     Dim newSubMarketSector As New CompanyName.SubMarketSector 

     If Not (currentDataReader.IsDBNull(currentDataReader.GetOrdinal("ID"))) Then 
      newSubMarketSector.ID = currentDataReader("ID") 
     End If 

     If Not (currentDataReader.IsDBNull(currentDataReader.GetOrdinal("Name"))) Then 
      newSubMarketSector.Name = currentDataReader("Name") 
     End If 

     Return newSubMarketSector 

    End Function 

End Class 

End Namespace 
+0

Вам придется передать его на ваш уровень доступа к данным при его создании. – Jack

ответ

0

Как насчет хранения ConnectionStrings в каждом WebApplication и передавая определенную строку подключения в библиотеку классов на создании экземпляра. Я не знаю, как вы разработали библиотеку классов (статические методы, singleton или что-то еще), но, возможно, вы можете передать их (каждый ConnectionString) в конструктор, чтобы установить переменную экземпляра, которую вы позже используете (так же, как раньше).

+0

Да, я думаю, я мог бы сделать это довольно легко. Является ли эта стандартная/лучшая практика обработки строк соединений, приведенных в этом примере? – Westicle

+0

Сказав, что я могу сделать это легко, это не кажется мне совершенно правильным. Каждый раз, когда я хочу вызвать функцию или подпрограмму, которая выполняет доступ к данным, мне нужно будет передать строку подключения. Это не соответствует Do not Repeat Yourself. – Westicle

+0

@Westicle Вам нужно сделать это только один раз за экземпляр. 'Dim class As New YourClass (connectionsString)' So в 'Sub New', вы можете присвоить свойству' _connectionString' его значение: '_connectionString = connectionString'. Надеюсь это поможет. – Jack