Retrieving records using ExecuteReader

Retrieving records is one of the most common database operations and the Data Access block provides several different ways to retrieve data. The ExecuteReader method allows us to execute a database command and returns an object implementing the IDataReader interface. This provides us a way to read records as a read-only and forward-only stream of rows.

The following code block shows records retrieval using ExecuteReader:

//Step 1: Create Default Database instance
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
//Step 2: Create Database Command - SQL String
DbCommand dbCommand = db.GetSqlStringCommand("SELECT CustomerID, FirstName, LastName FROM Customers WHERE CustomerID = @CustomerID");
//Step 3: Add Input Parameters
db.AddInParameter(dbCommand, "CustomerID", DbType.Int32, 1);
//Step 4: Execute Query
using (IDataReader reader = db.ExecuteReader(dbCommand))
{
// Read Data and map to business entity
}

We created an instance of Database using EnterpriseLibraryContainer. Since we are executing a query with parameters we created DbCommand object using the GetSqlStringCommand method of Database. Next, we added the input parameter using the AddInParameter method of Database, then we took the final step of executing the command using the ExecuteReader method. This method returns IDataReader. The data reader will be closed as it is wrapped with a using statement and the connection will be closed automatically.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.73.175