CHAPTER 21 ADO.NET PART I: THE CONNECTED LAYER
// A simple way to allow the transaction to succeed or not.
bool throwEx = true;
string userAnswer = string.Empty;
Console.Write("Do you want to throw an exception (Y or N): ");
userAnswer = Console.ReadLine();
if (userAnswer.ToLower() == "n")
{
throwEx = false;
}
InventoryDAL dal = new InventoryDAL();
dal.OpenConnection(@"Data Source=(local)\SQLEXPRESS;Integrated Security=SSPI;" +
"Initial Catalog=AutoLot");
// Process customer 333.
dal.ProcessCreditRisk(throwEx, 333);
}
Console.WriteLine("Check CreditRisk table for results");
Console.ReadLine();
If you were to run your program and elect to throw an exception, you would find that Homer is not
removed from the Customers table because the entire transaction has been rolled back. However, if you
did not throw an exception, you would find that Customer ID 333 is no longer in the Customers table and
has been placed in the CreditRisks table instead.
Source Code You can find the AdoNetTransaction project under the Chapter 21 subdirectory.
Summary
ADO.NET is the native data access technology of the .NET platform, and you can use it in three distinct
manners: connected, disconnected, or through the Entity Framework. In this chapter, you examined the
connected layer and learned the role of data providers, which are essentially concrete implementations
of several abstract base classes (in the System.Data.Common namespace) and interface types (in the
System.Data namespace). You also saw that it is possible to build a provider-neutral code base using the
ADO.NET data provider factory model.
You also learned that you can use connection objects, transaction objects, command objects, and
data reader objects of the connected layer to select, update, insert, and delete records. Also, recall that
command objects support an internal parameter collection, which you can use to add some type safety
to your SQL queries; these also prove quite helpful when triggering stored procedures.
858