2016-09-30 99 views
0

我有一個使用ASP.NET MVC的項目,並遵循三層體系結構。我想添加一個類庫,該類庫將包含一個將包含連接字符串的基類,並且在子類中必須通過將數據源作爲字符串傳遞來調用連接字符串。ASP.NET MVC無實體框架數據庫連接

基類:

public class DALConnection { 
    public SqlConnection con = new SqlConnection("Data Source=ABC;Initial Catalog=HotelMgmt;Integrated Security=True"); 
} 

子類:

public class DataAccessOperation: DALConnection { 
    // Some code 
} 

取而代之的是我想通過子類的連接字符串傳遞給基類的字符串。

回答

1

你認爲你可以使用構造函數來做到這一點嗎? (如下)

基類:

public class DALConnection { 

    public SqlConnection con; 

    public DALConnection(string connectionString) 
    { 
      con = new SqlConnection(connectionString); 
    } 

} 

兒童類:

public class DataAccessOperation: DALConnection { 

    //Some code 
    public DataAccessOperation() : base("Data Source=ABC;Initial Catalog=HotelMgmt;Integrated Security=True") 
    { 

    } 
} 
1

使用構造,以通過連接的字符串和具有派生類調用基構造。

基類

public class DALConnection { 
    protected string connectionString = "Data Source=ABC;Initial Catalog=HotelMgmt;Integrated Security=True"; 
    public SqlConnection con; 

    public DALConnection(string connectionString) { 
     if(connectionString!=null) 
      this.connectionString = connectionString; 
     con = new SqlConnection(this.connectionString); 
    } 
} 

子類:

public class DataAccessOperation: DALConnection { 

    DataAccessOperation(string connectionString) : base(connectionString) { 
    } 

} 
0

public class DALConnection 
{ 
     public DALConnection(string _conString) 
     { 
      if(!String.IsNullOrEmpty(_conString)) 
      { 
       con=new SqlConnection(_conString); 
      } 
      else 
      { 
       //error handling 
      } 
     }  

     private SqlConnection con; 

} 

public class DataAccessOperation: DALConnection 
{ 
     public DataAccessOperation (string _conString) :base (_conString) 
     { 
     } 


} 
相關問題