我維持其使用經典ADO.NET作爲現有的代碼數據訪問technology.The現有C#應用程序創建SqlConnection
和SqlCommand
對象EVERY單個時間與一些相互作用的新實例該數據庫是必需的。爲了簡單起見,我寫了一個小類來簡化這個過程,以防止代碼重複,但我不是ADO.NET的專家,所以我想問你是否可以查看我的代碼,並讓我知道如果我錯過了任何ADO.NET最佳做法或如果下面的代碼可以以任何負面影響DB操作:ADO.NET數據訪問層
using System;
using System.Data;
using System.Data.SqlClient;
namespace MyApp.DataAccess
{
public class DataAccessLayer : IDisposable
{
private SqlConnection _connection = new SqlConnection();
private SqlCommand _command = new SqlCommand();
public string ConnectionString
{
get { return DBConfig.ConnectionString; }
}
public SqlCommand Command
{
get { return _command; }
set { _command = value; }
}
public SqlConnection SQLConnection
{
get
{
if(_connection == null || _connection.State == ConnectionState.Closed)
{
_connection = new SqlConnection(ConnectionString);
_connection.Open();
}
return _connection;
}
}
public void SetCommand(string commandText,CommandType commandType)
{
_command = new SqlCommand(commandText, SQLConnection);
_command.CommandType = commandType;
}
public void Dispose()
{
if (_connection != null)
_connection.Dispose();
if (_command != null)
_command.Dispose();
}
}
}
該類防止您使用它總是建議'using'語句。它封裝了實現'IDisposable'的對象,應該儘快處理。這也關閉了連接。使用你班級的人會忘記這一點。 –
但是這就是爲什麼我繼承IDisposable並使用Dispose方法關閉連接的原因。或者這不是一回事? –
呃,其實是的。但是我不認爲像這樣的課程太多了。它鼓勵人們重複使用它,而不是在完成時始終處理它。他們將爲每個表單或應用程序創建一個'DataAccessLayer'實例,甚至可能是'static'並且每次都重用它。 –