Ado. NET with DbConnection, you can create dbcommand,begintransaction create dbtransaction with DbConnection CreateCommand
can be very convenient to implement the factory model, the operation of different databases.
But dbdataadapter this important object cannot be created by dbconnection or DbCommand, nor can it be instantiated, it must be created with an explicit class of SqlDataReader, which means that the method that gets the data cannot be implemented in the base class
Here are two solutions:
1. Only our own flexibility, manually determine the type of dbconnection, and return the corresponding dbdataadapter, although relatively stupid, but can barely achieve the purpose of simplifying the inheritance class, the code is as follows:
PrivateDbDataAdapter Createdataadapter () {if(conprivate isSystem.Data.SqlClient.SqlConnection)return NewSystem.Data.SqlClient.SqlDataAdapter (); if(conprivate isSybase.Data.AseClient.AseConnection)return NewSybase.Data.AseClient.AseDataAdapter (); if(conprivate isMySql.Data.MySqlClient.MySqlConnection)return NewMySql.Data.MySqlClient.MySqlDataAdapter (); Throw Newnotimplementedexception (); }
where Conprivate is DbConnection
2. In another way, the DataTable has a load method that can use IDataReader to get the data, and IDataReader can be created using DbCommand without the problem of DbDataAdapter not being instantiated. This allows you to implement methods for getting data in the base class.
It is important to note that the use of datatable.load (IDataReader DR) to obtain data, will bring a variety of restrictions (can not be empty, self-increment columns, read-only columns, etc.), in the code will be very inconvenient.
However, we know that the Fill method inside, but also through the dbdatareader to achieve the filling data, why the same Dbdatareader,fill method out of the DataTable there is no restriction?
Using reflector to view the Fill method, it is possible to use the following code to implement the method of acquiring data in the base class without taking the constraints
IDbCommand com = conprivate.createcommand (); = com. ExecuteReader (); New DataSet (); New DataTable (); Ds. Tables.add (DT); Ds. Load (DR, loadoption.overwritechanges, DT); false ; return DT;