Visual Programming
Lecture 5
Visual Studio & C#
Outline
• ADO .NET
• ADO .NET Connected
• ADO .NET Disconnected
• Strongly Type Dataset
• Entity Framework
ADO.NET
• ADO.NET stands for ActiveX Data Object. ADO.NET is a set of classes that expose
data access services for .NET Framework programmers. ADO.NET provides a rich
set of components for creating distributed, data-sharing applications. It is an
integral part of the .NET Framework, providing access to relational, XML, and
application data.
• ADO.NET provides consistent access to data sources such as SQL Server and XML,
and to data sources exposed through OLE DB and ODBC. Data-sharing consumer
applications can use ADO.NET to connect to these data sources and retrieve,
handle, and update the data that they contain.
• ADO.NET separates data access from data manipulation into discrete components
that can be used separately or in tandem. ADO.NET includes .NET Framework data
providers for connecting to a database, executing commands, and retrieving
results. Those results are either processed directly, placed in an ADO.NET DataSet
object in order to be exposed to the user in an ad hoc manner, combined with
data from multiple sources, or passed between tiers. The DataSet object can also
be used independently of a .NET Framework data provider to manage data local to
the application or sourced from XML.
Various Connection Architectures
There are the following two types of connection
architectures in ADO.NET:
Connected architecture: the application remains
connected with the database throughout the
processing.
Disconnected architecture: the application
automatically connects/disconnects during the
processing. The application uses temporary data on
the application side called a DataSet.
Strongly Typed DataSets
• Along with late bound access to values through weakly typed
variables, the DataSet provides access to data through a strongly
typed metaphor. Tables and columns that are part of
the DataSet can be accessed using user-friendly names and strongly
typed variables.
• A typed DataSet is a class that derives from a DataSet. As such, it
inherits all the methods, events, and properties of a DataSet.
Additionally, a typed DataSet provides strongly typed methods,
events, and properties. This means you can access tables and
columns by name, instead of using collection-based methods. Aside
from the improved readability of the code, a typed DataSet also
allows the Visual Studio .NET code editor to automatically complete
lines as you type.
• Additionally, the strongly typed DataSet provides access to values
as the correct type at compile time. With a strongly typed DataSet,
type mismatch errors are caught when the code is compiled rather
than at run time.
Understanding ADO.NET and it's class library
Introduction of LINQ to Entity
• LINQ to Entities provides Language-Integrated Query (LINQ) support that
enables developers to write queries against the Entity Framework
conceptual model using Visual Basic or Visual C#. Queries against the
Entity Framework are represented by command tree queries, which
execute against the object context. LINQ to Entities converts Language-
Integrated Queries (LINQ) queries to command tree queries, executes the
queries against the Entity Framework, and returns objects that can be
used by both the Entity Framework and LINQ. The following is the process
for creating and executing a LINQ to Entities query:
• Construct an ObjectQuery<T> instance from ObjectContext.
• Compose a LINQ to Entities query in C# or Visual Basic by using
the ObjectQuery<T>instance.
• Convert LINQ standard query operators and expressions to command
trees.
• Execute the query, in command tree representation, against the data
source. Any exceptions thrown on the data source during execution are
passed directly up to the client.
• Return query results back to the client.
Constructing an ObjectQuery Instance
• The ObjectQuery<T> generic class represents a query
that returns a collection of zero or more typed entities.
An object query is typically constructed from an
existing object context, instead of being manually
constructed, and always belongs to that object context.
This context provides the connection and metadata
information that is required to compose and execute
the query. The ObjectQuery<T> generic class
implements the IQueryable<T> generic interface,
whose builder methods enable LINQ queries to be
incrementally built. You can also let the compiler infer
the type of entities by using the C# var keyword.
Composing the Queries
• Instances of the ObjectQuery<T> generic class, which
implements the generic IQueryable<T>interface, serve
as the data source for LINQ to Entities queries. In a
query, you specify exactly the information that you
want to retrieve from the data source. A query can also
specify how that information should be sorted,
grouped, and shaped before it is returned. In LINQ, a
query is stored in a variable. This query variable takes
no action and returns no data; it only stores the query
information. After you create a query you must execute
that query to retrieve any data.
Query Conversion
• To execute a LINQ to Entities query against the Entity Framework, the LINQ query must be
converted to a command tree representation that can be executed against the Entity Framework.
• LINQ to Entities queries are comprised of LINQ standard query operators (such as Select, Where,
and GroupBy) and expressions (x > 10, Contact.LastName, and so on). LINQ operators are not
defined by a class, but rather are methods on a class. In LINQ, expressions can contain anything
allowed by types within the System.Linq.Expressions namespace and, by extension, anything that
can be represented in a lambda function. This is a superset of the expressions that are allowed by
the Entity Framework, which are by definition restricted to operations allowed on the database,
and supported by ObjectQuery<T>.
• In the Entity Framework, both operators and expressions are represented by a single type hierarchy,
which are then placed in a command tree. The command tree is used by the Entity Framework to
execute the query. If the LINQ query cannot be expressed as a command tree, an exception will be
thrown when the query is being converted. The conversion of LINQ to Entities queries involves two
sub-conversions: the conversion of the standard query operators, and the conversion of the
expressions.
• There are a number of LINQ standard query operators that do not have a valid translation in LINQ to
Entities. Attempts to use these operators will result in an exception at query translation time. For a
list of supported LINQ to Entities operators.
• In general, expressions in LINQ to Entities are evaluated on the server, so the behavior of the
expression should not be expected to follow CLR semantics.
Query Execution
After the LINQ query is created by the user, it is converted to a representation that is
compatible with the Entity Framework (in the form of command trees), which is then
executed against the data source. At query execution time, all query expressions (or
components of the query) are evaluated on the client or on the server. This includes
expressions that are used in result materialization or entity projections.
Materialization
Materialization is the process of returning query results back to the client as CLR
types. In LINQ to Entities, query results data records are never returned; there is
always a backing CLR type, defined by the user or by the Entity Framework, or
generated by the compiler (anonymous types). All object materialization is performed
by the Entity Framework. Any errors that result from an inability to map between the
Entity Framework and the CLR will cause exceptions to be thrown during object
materialization.
• Query results are usually returned as one of the following:
• A collection of zero or more typed entity objects or a projection of complex types
defined in the conceptual model.
• CLR types that are supported by the Entity Framework.
• Inline collections.
• Anonymous types.
LINQ and ADO.NET
Today, many business developers must use two (or more) programming
languages: a high-level language for the business logic and presentation layers
(such as Visual C# or Visual Basic), and a query language to interact with the
database (such as Transact-SQL). This requires the developer to be proficient
in several languages to be effective, and also causes language mismatches in
the development environment. For example, an application that uses a data
access API to execute a query against a database specifies the query as a
string literal by using quotation marks. This query string is un-readable to the
compiler and is not checked for errors, such as invalid syntax or whether the
columns or rows it references actually exist. There is no type checking of the
query parameters and no IntelliSense support, either.
Language-Integrated Query (LINQ) enables developers to form set-based
queries in their application code, without having to use a separate query
language. You can write LINQ queries against various enumerable data
sources (that is, a data source that implements the IEnumerableinterface),
such as in-memory data structures, XML documents, SQL databases, and
DataSetobjects. Although these enumerable data sources are implemented in
various ways, they all expose the same syntax and
LINQ and ADO.NET
• language constructs. Because queries can be formed in the programming language
itself, you do not have to use another query language that is embedded as string
literals that cannot be understood or verified by the compiler. Integrating queries
into the programming language also enables Visual Studio programmers to be
more productive by providing compile-time type and syntax checking, and
IntelliSense. These features reduce the need for query debugging and error fixing.
• Transferring data from SQL tables into objects in memory is often tedious and
error-prone. The LINQ provider implemented by LINQ to DataSet and LINQ to SQL
converts the source data into IEnumerable-based object collections. The
programmer always views the data as an IEnumerablecollection, both when you
query and when you update. Full IntelliSense support is provided for writing
queries against those collections.
• There are three separate ADO.NET Language-Integrated Query (LINQ)
technologies: LINQ to DataSet, LINQ to SQL, and LINQ to Entities. LINQ to DataSet
provides richer, optimized querying over the DataSet and LINQ to SQL enables you
to directly query SQL Server database schemas, and LINQ to Entities allows you to
query an Entity Data Model.
The following diagram provides an overview of how the ADO.NET LINQ technologies
relate to high-level programming languages and LINQ-enabled data sources.
What is Entity Framework
• Microsoft’s ORM (object relation mapper)
– Entity Framework is an object-relational mapper
(O/RM) that enables .NET developers to work with
a database using .NET objects. It eliminates the
need for most of the data-access code that
– developers usually need to write.
EF implements many popular ORM features:
Mapping of POCO entity classes which do not depend on any EF
types
Automatic change tracking
Identity resolution and Unit of Work
Eager, lazy and explicit loading
Translation of strongly-typed queries using LINQ (Language
Integrated Query)
Rich mapping capabilities, including support for:
One-to-one, one-to-many and many-to-many relationships
Inheritance (table per hierarchy, table per type and table per
concrete class)
Complex types
Stored procedures
A visual designer to create entity models.
A "Code First" experience to create entity models by writing code.
Models can either be generated from existing databases and then
hand-edited, or they can be created from scratch and then used to
generate new databases.
Integration with .NET Framework application models, including
ASP.NET, and through databinding, with WPF and WinForms.
Database connectivity based on ADO.NET and numerous providers
available to connect to SQL Server, Oracle, MySQL, SQLite,
PostgreSQL, DB2, etc.
How the Entity Framework works
C24, Slide 18
Benefits
• Eliminates disconnect between code & database
– No sql statements in code
– Use LINQ, Intellisense
• Can use SQL
• Find one person:
– Sql:
• string sql = "select * from students where id = @Id";
– LINQ
• Student student = db.Students.Find(id);
Benefits
• VS wizards can:
– Create models from
database
– Create database from model
– Create model and database
from db.model
– Create MVC controller and
views from models
Drawbacks
• Microsoft propriety technology
– Not useful outside MS universe
• LINQ query syntax different than SQL
– Better in some ways
• Synchronization between database and entity
objects
– Change database
– Rebuild entity objects