Chapter 12 Guaranteeing Data Integrity 209Chapter 12 Quick Reference Process statements using a local transaction Open a connection to a database using SqlConnection.. As the primary da
Trang 1// - Create the withdrawal and deposit connections
using (SqlConnection sourceLink =
new SqlConnection(GetConnectionString()))
{
using (SqlConnection destLink =
new SqlConnection(GetConnectionString()))
{
// - Lots of database-related code here
}
}
2 Surround the two nested using blocks with a third outer using block.
using (TransactionScope envelope = new TransactionScope())
{
// - The two original nested using blocks appear here
}
This statement block creates the TransactionScope, which is the object responsible for
managing the distributed transaction
3 Just after the “Transfer complete Commit the transaction” comment, add the following
line:
envelope.Complete();
This method call commits the entire transaction
4 Run the program In the local-transaction sample earlier in this chapter, attempting to
overdraw funds caused the transaction to fail in the first half of the two-part update: the withdrawal portion You can force a failure in the second half of the transaction by selecting a transfer in the opposite direction and entering a negative value (with an ab-solute value that exceeds the target account) in the Transfer Amount field
Select From Savings To Checking as the transfer type and enter -1000 (negative 1000)
in the Transfer Amount field—or any value that, if positive, would exceed the balance
in the checking account Select the Use A Distributed Transaction field and then click Transfer The error that occurs triggers a rollback of the distributed transaction due to a check constraint failure in the deposit portion (the second half) of the transaction
Trang 2Chapter 12 Guaranteeing Data Integrity 207
Processing with a Distributed Transaction: Visual Basic
Note This exercise uses the “Chapter 12 VB” sample project and continues from where the pre-vious exercise in this chapter left off.
1 Open the code for the AccountTransfer class Locate the TransferDistributed function
This code performs a transfer between two bank account records using a distributed
transaction The body of the routine hosts two nested Using blocks.
' - Create the withdrawal and deposit connections
Using sourceLink As SqlConnection =
New SqlConnection(GetConnectionString())
Using destLink As SqlConnection =
New SqlConnection(GetConnectionString())
' - Lots of database-related code here
End Using
End Using
2 Surround the two nested Using blocks with a third outer Using block.
Using envelope As TransactionScope = New TransactionScope()
' - The two original nested using blocks appear here
End Using
This statement block creates the TransactionScope, which is the object responsible for
managing the distributed transaction
3 Just after the “Transfer complete Commit the transaction” comment, add the following
line:
envelope.Complete()
This method call commits the entire transaction
Trang 3Transfer The error that occurs triggers a rollback of the distributed transaction due to a check constraint failure in the deposit portion (the second half) of the transaction
Summary
This chapter introduced the SqlTransaction class and its distributed counterpart, TransactionScope
Both tools allow you to treat multiple discrete database updates as a single, undivided whole This provides a greater level of data reliability when the risks associated with a partial data update are high
ADO.NET’s disconnected model lends itself well to the optimistic concurrency data locking model It’s a common scenario for systems where the chance of simultaneous updates to a single record is very low For situations where pessimistic concurrency and a more preemp-tive record locking strategy have been the norm, ADO.NET might require you to try different ways of accomplishing the same tasks
Trang 4Chapter 12 Guaranteeing Data Integrity 209
Chapter 12 Quick Reference
Process statements using a local transaction Open a connection to a database using SqlConnection.
Call the connection object’s BeginTransaction method to
obtain the transaction object.
Call the necessary SQL statements for data modification,
including the transaction object in each SqlCommand Call the transaction object’s Commit method to save the
changes.
Roll back a local transaction Create a valid SqlConnection and process data
modifica-tion statements as needed.
Call the transaction object’s Rollback method.
Process statements using a distributed transaction Start the MSDTC if not already running.
Create an instance of TransactionScope.
Process your SQL statements as needed, excluding the
use of SqlTransaction.
If the transaction is successful, call the TransactionScope object’s Complete method.
Call the TransactionScope object’s Dispose method.
Trang 6Microsoft ADO NET 4 Step by Step
Part III
Entity Framework
Trang 8Chapter 13
Introducing the Entity Framework
After completing this chapter, you will be able to:
■
■ Understand the high-level concepts of the ADO.NET Entity Framework
■
■ Distinguish between the three main Entity Framework modeling layers
■
■ Identify the general relationships between database elements and parallel elements in the Entity Framework
ADO.NET has been included with the NET Framework since its initial release in 2002 As the primary data layer of the Framework, it provides great general-purpose access to external data sources Starting with Service Pack 1 of Visual Studio 2008 (and the associated NET Framework version 3.5), Microsoft enhanced ADO.NET with a library of additional
function-ality known as the Entity Framework (EF) The question is this: Why? Why would Microsoft
augment a system that already provided sufficient features to work with both internal and external data in a generic, convenient format?
This chapter answers that question by introducing the Entity Framework and its major con-ceptual components It focuses on the two primary benefits of using the Framework on top
of ADO.NET’s core data functionality: (1) the ability to focus on the conceptual view of how data fits together instead of on the physical view of how it is stored in the database; and (2) the move away from the database-centric reality of independent tables joined in relation-ship toward a true object-oriented model in which related data values are treated as integral members of each other’s data worldviews
Note The four EF-related chapters in this book offer only a brief introduction to the flexible and extensive Entity Framework For expanded coverage of the Framework and how to use it
in your projects, review the Visual Studio online help The Microsoft Press book Programming
the Microsoft® ADO.NET Entity Framework provides a more detailed exploration of EF and its
components.
Understanding the Entity Framework
ADO.NET provides convenient programmer access to content located in an external data source or crafted within the application One of the data layer’s core strengths is its
capabil-ity to simulate the logical implementation of the underlying data source Database tables
Trang 9When working with tables of customers and orders, an associated DataSet will often con-tain Customer and Order DataTable objects that are little more than local copies of the true
tables Although this benefit is very useful for developers focused on a specific database schema, it is also a disadvantage, especially when changes to the external schema must be
constantly reflected in code The table-specific focus of the DataSet also forces applications
to work with data according to the dictates and limitations of the database, instead of on the enhanced features that languages such as C# and Visual Basic bring to the data processing table Additionally, ADO.NET’s use of generic object collections for row values removes the strongly typed benefits of programming in NET
Note Visual Studio 2005 and version 2.0 of the NET Framework introduced strongly typed
DataSets These wizard-generated classes, derived from DataSet and ADO.NET’s other
discon-nected table classes, added imported table and column definitions as true class members
Strongly typed data sets are still available in Visual Studio 2010 However, the Entity Framework provides enhanced database interaction capabilities and additional features that often make it a better option for defining strongly typed views of external data Strongly typed data sets are not discussed further in this book.
The Entity Framework helps resolve such issues by putting the focus on the conceptual
implementation of the data; a class-based view of how all the data works together Instead
of working with distinct table records that refer to each other’s records indirectly through foreign key values, EF objects expose these relationships as true object-oriented class
mem-berships Where a DataSet may contain separate Customer and Order tables that need to have their records joined manually in code, a Customer entity class generated by the Entity Framework includes an OrderEntries member, with each customer instance already aware of
its associated orders Foreign keys are still important, but the Framework figures out how to use them, leaving code free to access the results in a true instance-based environment
Trang 10Chapter 13 Introducing the Entity Framework 215 Defining the Entity Framework’s Terms
The Entity Framework works with different types of flat, relational, and hierarchical data sources—not just traditional databases such as SQL Server—so the names used for the dif-ferent components of the Framework were selected to reflect those difdif-ferent usage options Still, in light of its standard ADO.NET underpinnings and its excellent support for SQL Server and similar databases, it is helpful to understand its features as they relate to relational data-base concepts
■
■ Model The Entity Framework is, above all, a system for designing conceptual
mod-els of your data These modmod-els are saved in an XML format from which the Framework generates the specific source code classes All terms defined here (entity, association, and so on) are primarily model-based, although the Framework generates classes and code that makes them more than just items in a model diagram
■
■ Entity The core of the Entity Framework is, naturally, the Entity With its ADO.NET
core, you might think, incorrectly, that an entity finds its parallel in the DataSet or
DataTable Instead, the parallel for an entity is a single table row, a record, a DataRow
A customer entity is a single customer, with a distinct name, address, set of orders, and
so on The Framework generates the custom classes (known as Entity Types) from which
specific entity objects are instantiated
■
■ Entities The plural form of an entity has a separate existence in the Entity Framework,
implemented as a generic collection of a specific entity Similar in concept to a table
or a DataTable, entities are created by the Framework to expose enumerable instances
of a specific custom entity This parent-child relationship smoothes the transition from table-row-style database content to inheritable class-based data management
■
■ Property The field or column members of an entity (similar to DataColumn instances
in a DataTable) are known as properties This makes sense because they are
imple-mented as standard class properties, complete with configurable getters and setters
One or more properties in an entity are designated as the entity key, which uniquely
defines each entity All entities require an entity key Multiple properties can be defined
together as a complex type, sort of a user-defined data type for entities.
■
■ Association A relationship established between two entities is known as an
associa-tion, and is defined through an association type Similar to a database-level table join
or a DataRelation in standard ADO.NET, associations define the single or multicolumn
connections between different entities The properties on either end of the
relation-ship are known as association ends The cardinality of an association (or in EF parlance,
the multiplicity of its association endpoints; whether the association is one-to-one, one-to-many, and so on) helps determine how the association exposes data Unlike the
DataRelation implementation, associations are true bidirectional access points between
entity instances An entity can exist even if the tables that provide the content for asso-ciated entities lack a database-level join specification