System.Data.Dll 剖析

System.Data.Dll 剖析

 

先看下一张类结构

 

 

接下来通过Reflector工具反编译System.Date.Dll中相关类如下

IDbConnection

代码
public interface IDbConnection : IDisposable

{

    
// Methods

    IDbTransaction BeginTransaction();

    IDbTransaction BeginTransaction(IsolationLevel il);

    
void ChangeDatabase(string databaseName);

    
void Close();

    IDbCommand CreateCommand();

    
void Open();

 

    
// Properties

    
string ConnectionString { getset; }

    
int ConnectionTimeout { get; }

    
string Database { get; }

    ConnectionState State { 
get; }

}

 DbConnection

代码
public abstract class DbConnection : Component, IDbConnection, IDisposable

{

    
// Fields

    
private StateChangeEventHandler _stateChangeEventHandler;

 

    
// Events

    [ResDescription(
"DbConnection_StateChange"), ResCategory("DataCategory_StateChange")]

    
public event StateChangeEventHandler StateChange;

 

    
// Methods

    
protected DbConnection();

    
protected abstract DbTransaction BeginDbTransaction(IsolationLevel isolationLevel);

    
public DbTransaction BeginTransaction();

    
public DbTransaction BeginTransaction(IsolationLevel isolationLevel);

    
public abstract void ChangeDatabase(string databaseName);

    
public abstract void Close();

    
public DbCommand CreateCommand();

    
protected abstract DbCommand CreateDbCommand();

    
public virtual void EnlistTransaction(Transaction transaction);

    
public virtual DataTable GetSchema();

    
public virtual DataTable GetSchema(string collectionName);

    
public virtual DataTable GetSchema(string collectionName, string[] restrictionValues);

    
protected virtual void OnStateChange(StateChangeEventArgs stateChange);

    
public abstract void Open();

    IDbTransaction IDbConnection.BeginTransaction();

    IDbTransaction IDbConnection.BeginTransaction(IsolationLevel isolationLevel);

    IDbCommand IDbConnection.CreateCommand();

 

    
// Properties

    [ResCategory(
"DataCategory_Data"), DefaultValue(""), RecommendedAsConfigurable(true), RefreshProperties(RefreshProperties.All)]

    
public abstract string ConnectionString { getset; }

    [ResCategory(
"DataCategory_Data")]

    
public virtual int ConnectionTimeout { get; }

    [ResCategory(
"DataCategory_Data")]

    
public abstract string Database { get; }

    [ResCategory(
"DataCategory_Data")]

    
public abstract string DataSource { get; }

    
protected virtual DbProviderFactory DbProviderFactory { get; }

    
internal DbProviderFactory ProviderFactory { get; }

    [Browsable(
false)]

    
public abstract string ServerVersion { get; }

    [Browsable(
false), ResDescription("DbConnection_State")]

    
public abstract ConnectionState State { get; }

}

SqlConnection

代码
[DefaultEvent("InfoMessage")]

public sealed class SqlConnection : DbConnection, ICloneable

{

    
// Fields

    
private bool _AsycCommandInProgress;

    
private int _closeCount;

    
private bool _collectstats;

    
private static readonly DbConnectionFactory _connectionFactory;

    
private bool _fireInfoMessageEventOnUserErrors;

    
private DbConnectionInternal _innerConnection;

    
private static int _objectTypeCount;

    
private DbConnectionPoolGroup _poolGroup;

    
private SqlDebugContext _sdc;

    
internal SqlStatistics _statistics;

    
private DbConnectionOptions _userConnectionOptions;

    
private static readonly object EventInfoMessage;

    
internal static readonly CodeAccessPermission ExecutePermission;

    
internal readonly int ObjectID;

 

    
// Events

    [ResCategory(
"DataCategory_InfoMessage"), ResDescription("DbConnection_InfoMessage")]

    
public event SqlInfoMessageEventHandler InfoMessage;

 

    
// Methods

    
static SqlConnection();

    
public SqlConnection();

    
private SqlConnection(SqlConnection connection);

    
public SqlConnection(string connectionString);

    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]

    
internal void Abort(Exception e);

    
internal void AddPreparedCommand(SqlCommand cmd);

    
internal void AddWeakReference(object value, int tag);

    
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel);

    
public SqlTransaction BeginTransaction();

    
public SqlTransaction BeginTransaction(IsolationLevel iso);

    
public SqlTransaction BeginTransaction(string transactionName);

    
public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName);

    
public override void ChangeDatabase(string database);

    
public static void ChangePassword(string connectionString, string newPassword);

    
internal static void CheckGetExtendedUDTInfo(SqlMetaDataPriv metaData, bool fThrow);

    
internal void CheckSQLDebug();

    [SecurityPermission(SecurityAction.Demand, Flags
=SecurityPermissionFlag.UnmanagedCode)]

    
private void CheckSQLDebug(SqlDebugContext sdc);

    
private void CheckSQLDebugOnConnect();

    
public static void ClearAllPools();

    
public static void ClearPool(SqlConnection connection);

    
public override void Close();

    
private void CompleteOpen();

    
private string ConnectionString_Get();

    
private void ConnectionString_Set(string value);

    
private void CopyFrom(SqlConnection connection);

    
public SqlCommand CreateCommand();

    
protected override DbCommand CreateDbCommand();

    
private static CodeAccessPermission CreateExecutePermission();

    
protected override void Dispose(bool disposing);

    
private void DisposeMe(bool disposing);

    
public void EnlistDistributedTransaction(ITransaction transaction);

    
private void EnlistDistributedTransactionHelper(ITransaction transaction);

    
public override void EnlistTransaction(Transaction transaction);

    
internal static string FixupDatabaseTransactionName(string name);

    
internal byte[] GetBytes(object o);

    
internal byte[] GetBytes(object o, out Format format, out int maxSize);

    
private DbMetaDataFactory GetMetaDataFactory(DbConnectionInternal internalConnection);

    
internal DbMetaDataFactory GetMetaDataFactoryInternal(DbConnectionInternal internalConnection);

    
internal SqlInternalConnection GetOpenConnection();

    
internal SqlInternalConnection GetOpenConnection(string method);

    
internal SqlInternalConnectionTds GetOpenTdsConnection();

    
internal SqlInternalConnectionTds GetOpenTdsConnection(string method);

    
public override DataTable GetSchema();

    
public override DataTable GetSchema(string collectionName);

    
public override DataTable GetSchema(string collectionName, string[] restrictionValues);

    
internal object GetUdtValue(object value, SqlMetaDataPriv metaData, bool returnDBNull);

    
private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, string sdiDllName, byte[] data);

    
internal void NotifyWeakReference(int message);

    
internal void OnError(SqlException exception, bool breakConnection);

    
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent);

    
public override void Open();

    
internal void PermissionDemand();

    
private static void RefreshMemoryMappedData(SqlDebugContext sdc);

    
internal void RemovePreparedCommand(SqlCommand cmd);

    
internal void RemoveWeakReference(object value);

    
public void ResetStatistics();

    
public IDictionary RetrieveStatistics();

    
internal void SetInnerConnectionEvent(DbConnectionInternal to);

    
internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from);

    
internal void SetInnerConnectionTo(DbConnectionInternal to);

    
object ICloneable.Clone();

    
private void UpdateStatistics();

    
internal void ValidateConnectionForExecute(string method, SqlCommand command);

    [Conditional(
"DEBUG")]

    
internal static void VerifyExecutePermission();

 

    
// Properties

    
internal bool AsycCommandInProgress { get; [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set; }

    
internal bool Asynchronous { get; }

    
internal int CloseCount { get; }

    
internal DbConnectionFactory ConnectionFactory { get; }

    
internal DbConnectionOptions ConnectionOptions { get; }

    [Editor(
"Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a""System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), ResDescription("SqlConnection_ConnectionString"), DefaultValue(""), RecommendedAsConfigurable(true), RefreshProperties(RefreshProperties.All), ResCategory("DataCategory_Data")]

    
public override string ConnectionString { getset; }

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResDescription(
"SqlConnection_ConnectionTimeout")]

    
public override int ConnectionTimeout { get; }

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResDescription(
"SqlConnection_Database")]

    
public override string Database { get; }

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(
true), ResDescription("SqlConnection_DataSource")]

    
public override string DataSource { get; }

    
protected override DbProviderFactory DbProviderFactory { get; }

    
public bool FireInfoMessageEventOnUserErrors { getset; }

    
internal bool HasLocalTransaction { get; }

    
internal bool HasLocalTransactionFromAPI { get; }

    
internal DbConnectionInternal InnerConnection { get; }

    
internal bool IsContextConnection { get; }

    
internal bool IsKatmaiOrNewer { get; }

    
internal bool IsShiloh { get; }

    
internal bool IsYukonOrNewer { get; }

    [ResDescription(
"SqlConnection_PacketSize"), ResCategory("DataCategory_Data"), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

    
public int PacketSize { get; }

    
internal TdsParser Parser { get; }

    
internal DbConnectionPoolGroup PoolGroup { getset; }

    [ResDescription(
"SqlConnection_ServerVersion"), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]

    
public override string ServerVersion { get; }

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(
false), ResDescription("DbConnection_State")]

    
public override ConnectionState State { get; }

    
internal SqlStatistics Statistics { get; }

    [DefaultValue(
false), ResDescription("SqlConnection_StatisticsEnabled"), ResCategory("DataCategory_Data")]

    
public bool StatisticsEnabled { getset; }

    
internal SqlConnectionString.TransactionBindingEnum TransactionBinding { get; }

    
internal SqlConnectionString.TypeSystem TypeSystem { get; }

    
internal DbConnectionOptions UserConnectionOptions { get; }

    [ResDescription(
"SqlConnection_WorkstationId"), ResCategory("DataCategory_Data"), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

    
public string WorkstationId { get; }

}

 

 

 IDbCommand

代码
public interface IDbCommand : IDisposable

{

    
// Methods

    
void Cancel();

    IDbDataParameter CreateParameter();

    
int ExecuteNonQuery();

    IDataReader ExecuteReader();

    IDataReader ExecuteReader(CommandBehavior behavior);

    
object ExecuteScalar();

    
void Prepare();

 

    
// Properties

    
string CommandText { getset; }

    
int CommandTimeout { getset; }

    CommandType CommandType { 
getset; }

    IDbConnection Connection { 
getset; }

    IDataParameterCollection Parameters { 
get; }

    IDbTransaction Transaction { 
getset; }

    UpdateRowSource UpdatedRowSource { 
getset; }

}

 DbCommand

代码
public abstract class DbCommand : Component, IDbCommand, IDisposable

{

    
// Methods

    
protected DbCommand();

    
public abstract void Cancel();

    
protected abstract DbParameter CreateDbParameter();

    
public DbParameter CreateParameter();

    
protected abstract DbDataReader ExecuteDbDataReader(CommandBehavior behavior);

    
public abstract int ExecuteNonQuery();

    
public DbDataReader ExecuteReader();

    
public DbDataReader ExecuteReader(CommandBehavior behavior);

    
public abstract object ExecuteScalar();

    
public abstract void Prepare();

    IDbDataParameter IDbCommand.CreateParameter();

    IDataReader IDbCommand.ExecuteReader();

    IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior);

 

    
// Properties

    [ResDescription(
"DbCommand_CommandText"), DefaultValue(""), RefreshProperties(RefreshProperties.All), ResCategory("DataCategory_Data")]

    
public abstract string CommandText { getset; }

    [ResCategory(
"DataCategory_Data"), ResDescription("DbCommand_CommandTimeout")]

    
public abstract int CommandTimeout { getset; }

    [ResCategory(
"DataCategory_Data"), ResDescription("DbCommand_CommandType"), DefaultValue(1), RefreshProperties(RefreshProperties.All)]

    
public abstract CommandType CommandType { getset; }

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResCategory(
"DataCategory_Data"), DefaultValue((stringnull), ResDescription("DbCommand_Connection"), Browsable(false)]

    
public DbConnection Connection { getset; }

    
protected abstract DbConnection DbConnection { getset; }

    
protected abstract DbParameterCollection DbParameterCollection { get; }

    
protected abstract DbTransaction DbTransaction { getset; }

    [EditorBrowsable(EditorBrowsableState.Never), DefaultValue(
true), DesignOnly(true), Browsable(false)]

    
public abstract bool DesignTimeVisible { getset; }

    [ResDescription(
"DbCommand_Parameters"), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false), ResCategory("DataCategory_Data")]

    
public DbParameterCollection Parameters { get; }

    IDbConnection IDbCommand.Connection { 
getset; }

    IDataParameterCollection IDbCommand.Parameters { 
get; }

    IDbTransaction IDbCommand.Transaction { 
getset; }

    [DefaultValue((
stringnull), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResDescription("DbCommand_Transaction")]

    
public DbTransaction Transaction { getset; }

    [ResCategory(
"DataCategory_Update"), ResDescription("DbCommand_UpdatedRowSource"), DefaultValue(3)]

    
public abstract UpdateRowSource UpdatedRowSource { getset; }

}

 

 

 SqlCommand

代码
[Designer("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), ToolboxItem(true), DefaultEvent("RecordsAffected")]

public sealed class SqlCommand : DbCommand, ICloneable

{

    
// Fields

    
private SqlConnection _activeConnection;

    
private bool _batchRPCMode;

    
private CachedAsyncState _cachedAsyncState;

    
private _SqlMetaDataSet _cachedMetaData;

    
private string _commandText;

    
private int _commandTimeout;

   
private CommandType _commandType;

    
private int _currentlyExecutingBatch;

    
private bool _designTimeInvisible;

    
private bool _dirty;

    
private EXECTYPE _execType;

    
private bool _hiddenPrepare;

    
private bool _inPrepare;

    
private SqlNotificationRequest _notification;

    
private bool _notificationAutoEnlist;

    
private static int _objectTypeCount;

    
private SmiEventSink_DeferedProcessing _outParamEventSink;

    
private List<SqlParameterCollection> _parameterCollectionList;

    
private SqlParameterCollection _parameters;

    
private volatile bool _pendingCancel;

    
private int _prepareHandle;

    
internal int _rowsAffected;

    
private _SqlRPC[] _rpcArrayOf1;

    
private List<_SqlRPC> _RPCList;

    
private CommandEventSink _smiEventSink;

    
private SmiRequestExecutor _smiRequest;

    
private SmiContext _smiRequestContext;

    
internal SqlDependency _sqlDep;

    
private _SqlRPC[] _SqlRPCBatchArray;

    
private StatementCompletedEventHandler _statementCompletedEventHandler;

    
private TdsParserStateObject _stateObj;

    
private SqlTransaction _transaction;

    
private UpdateRowSource _updatedRowSource;

    
internal static readonly string[] KatmaiProcParamsNames;

    
internal readonly int ObjectID;

    
internal static readonly string[] PreKatmaiProcParamsNames;

 

    
// Events

    [ResCategory(
"DataCategory_StatementCompleted"), ResDescription("DbCommand_StatementCompleted")]

    
public event StatementCompletedEventHandler StatementCompleted;

 

    
// Methods

    
static SqlCommand();

    
public SqlCommand();

    
private SqlCommand(SqlCommand from);

    
public SqlCommand(string cmdText);

    
public SqlCommand(string cmdText, SqlConnection connection);

    
public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction);

    
internal void AddBatchCommand(string commandText, SqlParameterCollection parameters, CommandType cmdType);

    [HostProtection(SecurityAction.LinkDemand, ExternalThreading
=true)]

    
public IAsyncResult BeginExecuteNonQuery();

    [HostProtection(SecurityAction.LinkDemand, ExternalThreading
=true)]

    
public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject);

    [HostProtection(SecurityAction.LinkDemand, ExternalThreading
=true)]

    
public IAsyncResult BeginExecuteReader();

    [HostProtection(SecurityAction.LinkDemand, ExternalThreading
=true)]

    
public IAsyncResult BeginExecuteReader(CommandBehavior behavior);

    [HostProtection(SecurityAction.LinkDemand, ExternalThreading
=true)]

    
public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject);

    [HostProtection(SecurityAction.LinkDemand, ExternalThreading
=true)]

    
public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior);

    [HostProtection(SecurityAction.LinkDemand, ExternalThreading
=true)]

    
public IAsyncResult BeginExecuteXmlReader();

    [HostProtection(SecurityAction.LinkDemand, ExternalThreading
=true)]

    
public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject);

    
private _SqlRPC BuildExecute(bool inSchema);

    
private void BuildExecuteSql(CommandBehavior behavior, string commandText, SqlParameterCollection parameters, ref _SqlRPC rpc);

    
internal string BuildParamList(TdsParser parser, SqlParameterCollection parameters);

    
private _SqlRPC BuildPrepare(CommandBehavior behavior);

    
private _SqlRPC BuildPrepExec(CommandBehavior behavior);

    
private void BuildRPC(bool inSchema, SqlParameterCollection parameters, ref _SqlRPC rpc);

    
private _SqlRPC BuildUnprepare();

    
public override void Cancel();

    
private void CheckNotificationStateAndAutoEnlist();

    
private void CheckThrowSNIException();

    
internal void ClearBatchCommand();

    
public SqlCommand Clone();

    
private SqlDataReader CompleteAsyncExecuteReader();

    
private object CompleteExecuteScalar(SqlDataReader ds, bool returnSqlValue);

    
private XmlReader CompleteXmlReader(SqlDataReader ds);

    
private int CountSendableParameters(SqlParameterCollection parameters);

    
protected override DbParameter CreateDbParameter();

    
public SqlParameter CreateParameter();

    
internal void DeriveParameters();

    
protected override void Dispose(bool disposing);

    
private void DisposeSmiRequest();

    
public int EndExecuteNonQuery(IAsyncResult asyncResult);

    
public SqlDataReader EndExecuteReader(IAsyncResult asyncResult);

    
public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult);

    
internal int ExecuteBatchRPCCommand();

    
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior);

    
public override int ExecuteNonQuery();

    
public SqlDataReader ExecuteReader();

    
public SqlDataReader ExecuteReader(CommandBehavior behavior);

    
internal SqlDataReader ExecuteReader(CommandBehavior behavior, string method);

    
public override object ExecuteScalar();

    
internal void ExecuteToPipe(SmiContext pipeContext);

    
public XmlReader ExecuteXmlReader();

    
private void FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, string resetOptionsString);

    
private string GetCommandText(CommandBehavior behavior);

    
private SqlParameterCollection GetCurrentParameterCollection();

    
internal SqlException GetErrors(int commandIndex);

    
private int GetParameterCount(SqlParameterCollection parameters);

    
private SqlParameter GetParameterForOutputValueExtraction(SqlParameterCollection parameters, string paramName, int paramCount);

    
internal int? GetRecordsAffected(int commandIndex);

    
private string GetResetOptionsString(CommandBehavior behavior);

    
private void GetRPCObject(int paramCount, ref _SqlRPC rpc);

    
private string GetSetOptionsString(CommandBehavior behavior);

    
private void GetStateObject();

    
private IAsyncResult InternalBeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior);

    
private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string endMethod);

    
private int InternalExecuteNonQuery(DbAsyncResult result, string methodName, bool sendToPipe);

    
private SqlDataReader InternalPrepare(CommandBehavior behavior);

    
private void InternalUnprepare(bool isClosing);

    
private void NotifyDependency();

    
internal void OnDoneProc();

    
internal void OnParameterAvailableSmi(SmiParameterMetaData metaData, ITypedGettersV3 parameterValues, int ordinal);

    
internal void OnParametersAvailableSmi(SmiParameterMetaData[] paramMetaData, ITypedGettersV3 parameterValues);

    
internal void OnReturnStatus(int status);

    
internal void OnReturnValue(SqlReturnValue rec);

    
internal void OnStatementCompleted(int recordCount);

    
private ParameterDirection ParameterDirectionFromOleDbDirection(short oledbDirection);

    
public override void Prepare();

    
private void PropertyChanging();

    
private void PutStateObject();

    
public void ResetCommandTimeout();

    
private void RunExecuteNonQuerySmi(bool sendToPipe);

    
private void RunExecuteNonQueryTds(string methodName, bool async);

    
internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, string method);

    
internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, string method, DbAsyncResult result);

    
private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream);

    
private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, bool async);

    
private void SetUpRPCParameters(_SqlRPC rpc, int startCount, bool inSchema, SqlParameterCollection parameters);

    
private void SetUpSmiRequest(SqlInternalConnectionSmi innerConnection);

    
private static bool ShouldSendParameter(SqlParameter p);

    
private bool ShouldSerializeCommandTimeout();

    [SecurityPermission(SecurityAction.Assert, Infrastructure
=true)]

    
internal static string SqlNotificationContext();

    
object ICloneable.Clone();

    
internal void Unprepare(bool isClosing);

    
private static string UnquoteProcedureName(string name, out object groupNumber);

    
private static string UnquoteProcedurePart(string part);

    
private void ValidateAsyncCommand();

    
private void ValidateCommand(string method, bool async);

    
private void VerifyEndExecuteState(DbAsyncResult dbAsyncResult, string endMethod);

    
private void WaitForAsyncResults(IAsyncResult asyncResult);

 

    
// Properties

    
internal bool BatchRPCMode { getset; }

    
private CachedAsyncState cachedAsyncState { get; }

    [Editor(
"Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a""System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), RefreshProperties(RefreshProperties.All), ResCategory("DataCategory_Data"), ResDescription("DbCommand_CommandText"), DefaultValue("")]

    
public override string CommandText { getset; }

    [ResDescription(
"DbCommand_CommandTimeout"), ResCategory("DataCategory_Data")]

    
public override int CommandTimeout { getset; }

    [ResCategory(
"DataCategory_Data"), DefaultValue(1), ResDescription("DbCommand_CommandType"), RefreshProperties(RefreshProperties.All)]

    
public override CommandType CommandType { getset; }

    [DefaultValue((
stringnull), Editor("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a""System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), ResCategory("DataCategory_Data"), ResDescription("DbCommand_Connection")]

    
public SqlConnection Connection { getset; }

    
protected override DbConnection DbConnection { getset; }

    
protected override DbParameterCollection DbParameterCollection { get; }

    
protected override DbTransaction DbTransaction { getset; }

    [DefaultValue(
true), Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignOnly(true)]

    
public override bool DesignTimeVisible { getset; }

    
private CommandEventSink EventSink { get; }

    
internal int InternalRecordsAffected { getset; }

    
private SqlInternalConnectionSmi InternalSmiConnection { get; }

    
private SqlInternalConnectionTds InternalTdsConnection { get; }

    
internal bool IsDirty { getset; }

    
private bool IsPrepared { get; }

    
private bool IsShiloh { get; }

    
private bool IsUserPrepared { get; }

    
internal _SqlMetaDataSet MetaData { get; }

    [Browsable(
false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResCategory("DataCategory_Notification"), ResDescription("SqlCommand_Notification")]

    
public SqlNotificationRequest Notification { getset; }

    [DefaultValue(
true), ResDescription("SqlCommand_NotificationAutoEnlist"), ResCategory("DataCategory_Notification")]

    
public bool NotificationAutoEnlist { getset; }

    
private SmiEventSink_DeferedProcessing OutParamEventSink { get; }

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), ResCategory(
"DataCategory_Data"), ResDescription("DbCommand_Parameters")]

    
public SqlParameterCollection Parameters { get; }

    
internal SqlStatistics Statistics { get; }

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResDescription(
"DbCommand_Transaction"), Browsable(false)]

    
public SqlTransaction Transaction { getset; }

    [ResCategory(
"DataCategory_Update"), DefaultValue(3), ResDescription("DbCommand_UpdatedRowSource")]

    
public override UpdateRowSource UpdatedRowSource { getset; }

 

    
// Nested Types

    
private class CachedAsyncState

    {

        
// Fields

        
private int _cachedAsyncCloseCount;

        
private SqlConnection _cachedAsyncConnection;

        
private SqlDataReader _cachedAsyncReader;

        
private DbAsyncResult _cachedAsyncResult;

        
private RunBehavior _cachedRunBehavior;

        
private string _cachedSetOptions;

 

        
// Methods

        
internal CachedAsyncState();

        
internal bool IsActiveConnectionValid(SqlConnection activeConnection);

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]

        
internal void ResetAsyncState();

        
internal void SetActiveConnectionAndResult(DbAsyncResult result, SqlConnection activeConnection);

        
internal void SetAsyncReaderState(SqlDataReader ds, RunBehavior runBehavior, string optionSettings);

 

        
// Properties

        
internal SqlDataReader CachedAsyncReader { get; }

        
internal RunBehavior CachedRunBehavior { get; }

        
internal string CachedSetOptions { get; }

        
internal bool PendingAsyncOperation { get; }

    }

 

    
private sealed class CommandEventSink : SmiEventSink_Default

    {

        
// Fields

        
private SqlCommand _command;

 

        
// Methods

        
internal CommandEventSink(SqlCommand command);

        
internal override void BatchCompleted();

        
internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal);

        
internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues);

        
internal override void StatementCompleted(int rowsAffected);

    }

 

    
private enum EXECTYPE

    {

        UNPREPARED,

        PREPAREPENDING,

        PREPARED

    }

}

 

 DbProviderFactories

代码
public static class DbProviderFactories

{

    
// Fields

    
private static DataSet _configTable;

    
private static ConnectionState _initState;

    
private static object _lockobj;

    
private const string AssemblyQualifiedName = "AssemblyQualifiedName";

    
private const string Instance = "Instance";

    
private const string InvariantName = "InvariantName";

 

    
// Methods

    
static DbProviderFactories();

    
private static DataSet GetConfigTable();

    
public static DbProviderFactory GetFactory(DataRow providerRow);

    
public static DbProviderFactory GetFactory(string providerInvariantName);

    
public static DataTable GetFactoryClasses();

    
private static void Initialize();

}

 

 

 

接下再看一下常见的数据访问代码

 

代码
 

// Create a new database provider factory

DbProviderFactory factory 
=

DbProviderFactories.GetFactory(
"System.Data.SqlClient");

// Create the connection object

DbConnection conn 
= factory.CreateConnection();

// Initialize the connection string

conn.ConnectionString 
= "... connection string ...";

// Create the command object and set its properties

DbCommand comm 
= conn.CreateCommand();

comm.CommandText 
= "GetDepartments";

comm.CommandType 
= CommandType.StoredProcedure;

// Open the connection

conn.Open();

// Execute the command and save the results in a DataTable

DbDataReader reader 
= comm.ExecuteReader();

DataTable table 
= new DataTable();

table.Load(reader);

// Close the reader and the connection

reader.Close();

conn.Close();

DbProviderFactories其实是一个工厂类,他会根据数据连接类型实例化相应的connetion,command,DbProviderFactories. GetFactory()反编译出来的原代码可以看出结果,代码码如下

代码
public static DbProviderFactory GetFactory(string providerInvariantName)

{

    ADP.CheckArgumentLength(providerInvariantName, 
"providerInvariantName");

    DataSet configTable 
= GetConfigTable();

    DataTable table 
= (configTable != null? configTable.Tables["DbProviderFactories"] : null;

    
if (table != null)

    {

        DataRow providerRow 
= table.Rows.Find(providerInvariantName);

        
if (providerRow != null)

        {

            
return GetFactory(providerRow);

        }

    }

    
throw ADP.ConfigProviderNotFound();

}

其中return GetFactory(providerRow);这句话就不必要继续反编译下去了,只要理解他会跟据我们的需要返回相的类型即可,如上面的示例数据访问代码DbProviderFactories.GetFactory("System.Data.SqlClient")会返回SqlConnection对像。

通过下面这的概要类图可以帮助理解

 

posted @ 2011-01-19 16:54  赵一村  阅读(2176)  评论(1编辑  收藏  举报