Chapter One
Taking a New Approach to Data Access in ADO.NET 3.5
Visual Studio (VS) 2008 SP1 is a major upgrade to Visual Studio 2005 and the Visual Basic 8.0 and C# 2.0 languages. ADO.NET 3.5 introduces many new language and data access features to ADO .NET 2.0 and its DataSet-oriented programming model. The primary objectives of these additions are to:
Increase programmer productivity by reducing the amount of code required to complete a particular data-related task, such as querying and updating relational data sources, DataSets, or XML documents
Enable strong type-checking of query syntax for relational data and query resultsets
Reduce or eliminate what''s often called the impedance mismatch between the code for managing data, which usually involves Structured Query Language (SQL), and object-oriented (OO) programming
Provide data-intensive Windows form projects with a local, synchronizable data cache derived from SQL Server Compact Edition v3.5
Enhance DataSet integration with n-tier architecture
VS attempts to accomplish the preceding objectives with the following new LINQ language extentions to C# and VB, domain-specific implementations, and LINQ-related components or frameworks:
Language Integrated Query (LINQ) extensions to the Visual Basic 9.0 and C# 3.0 languages and compilers provide developers with a set of standard query operators to query a variety of data sources with a standard query language similar to SQL. LINQ extensions to VB and C# are said to implement the LINQ pattern.
LINQ to Objects is the default LINQ implementation, which enables developers to express and execute queries against in-memory collections that implement the IEnumerable or IQueryable interface.
LINQ to SQL (formerly DLinq) extensions to LINQ to Objects provide a basic object/relational mapping (O/RM) tool to generate and manage entity classes for business objects, and persist entity instances in SQL Server 200x tables.
LinqDataSource is an ASP.NET 3.5 server control for simplify binding other data-enabled Web controls to business objects created with LINQ to SQL.
In OO-speak, to persist means to save in-memory objects to and load them from a data store, which can be a relational, object or flat-file database, or an Extensible Markup Language (XML) or other type of file.
LINQ to DataSets is an extension that enables LINQ to execute queries with joins over DataTables of typed or untyped ADO.NET DataSets.
LINQ to XML (formerly XLinq) extensions to LINQ to Objects enable XML document processing with standard LINQ queries and constructing XML documents with a declarative syntax.
Entity Framework (EF), Entity Data Model (EDM), EntityClient .NET data provider for SQL Server 200x, Entity SQL (eSQL) query language, and related designers, wizards, and tools map a data store''s physical implementation to a conceptual schema. The conceptual schema supports an upper layer of custom business objects, which can represent a domain model.
LINQ to Entities is a LINQ implantation that generates eSQL to enable querying the Entity Framework''s Object Services layer with LINQ syntax.
EntityDataSource corresponds to a LinqDataSource control for business objects generated by EF''s EDM.
Following are a few of the most important new related technologies, frameworks, and implentations that take advantage of or enhance LINQ:
LINQ to XSD extensions to LINQ to XML deliver strong data-typing to LINQ to XML queries by reference to a formal or inferred XML schema for the source document. LINQ to XSD was an unsupported alpha version of an incubator project when this book was written.
ADO.NET Data Services Framework (formerly Project Astoria) enables developers to make data available as a simple Representational State Transfer (REST) Web service with Atom Publication (AtomPub or APP) format or JavaScript Object Notation (JSON) as the wire format. EF is Astoria''s preferred data source; LINQ to SQL or other LINQ-enabled data sources create read-only Astoria services.
ASP.NET Dynamic Data (DD) is a framework for autogenerating complete data-intensive Web sites from a LINQ to SQL or LINQ to Entities data source. DD is a highly enhanced version of an earlier project named BLINQ. DD can create an administrative Web site for a complex database in a few minutes by a process known as scaffolding. Ruby on Rails introducted Web developers to automated scaffolding.
Windows Communication Framework (WCF) Service templates simplify development of n-tier service-oriented applications that isolate the data-access tier from business object and presentation tiers by interposing a service layer. Astoria implements a string-based subset of LINQ query syntax. Astoria is an example of a LINQ-oriented framework that takes advantage of .NET 3.5 SP1 WCF templates.
Parallel LINQ (PLINQ) is a set of extensions to LINQ to Objects that enable parallel processing of LINQ queries on multi-core PCs. PLINQ was in the Community Technical Preview (CTP) stage when this book was written.
Hierarchical updates to typed DataSets with the TableAdapterManager.UpdateAll() method greatly reduce the amount of code required to update multiple related tables in the underlying database.
SQL Server Compact (SSCE) 3.5 enables local data caching with a lightweight in-process relational database management system. LINQ to SQL and EF can use SSCE 3.5 as a data source but prevent use of the graphic O/RM tools to edit the resulting entities.
Microsoft Synchronization Framework components implement occasionally connected systems (OCS) by synchronizing SSCE caches with SQL Server 200x databases.
The preceding list includes substantially more new data-related technologies and components than delivered by any .NET Framework and Visual Studio version since 1.0; this book covers all but the last four items. Examples demonstrate WCF service-oriented, n-tier architectures for Astoria projects that use LINQ to SQL or LINQ to Entities their data source. However, this book doesn''t attempt to cover other WCF features.
This chapter is an introduction to the two principal topics of this book: LINQ and the ADO.NET Entity framework.
Microsoft''s Server and Tools Division dropped EF and its components from the release-to-manufacturing (RTM) version Visual Studio 2008 on April 29, 2007. The ADO.NET Team subsequently released EF CTP and Beta editions with the intention of adding it to VS 2008 and .NET 3.5 in the first half of 2008. EF and EDM released with .NET 3.5 SP1 and VS 2008 SP1 on August 11, 2008. This book was written with the RTM versions of .NET 3.5 SP1 and VS 2008 SP1.
Language Integrated Query (LINQ)
LINQ is a revolutionary programming methodology that transforms the relationship between programs and data. LINQ defines a .NET application programming interface (API) and set of extensions to the Visual Basic and C# languages that enables querying diverse data types with a single syntax that''s similar to Structured Query Language (SQL). Writing queries in your .NET language of choice enables strong typing and support for programmer productivity enhancing features, such as statement completion and IntelliSense.
The LINQ framework permits custom extensions to support common data types or exotic data domains. When this book was written, the .NET Framework and Visual Studio 2008 supported LINQ implementations for querying collections of in-memory objects (LINQ to Objects), tables of SQL Server 200x databases (LINQ to SQL), ADO.NET DataSets (LINQ to DataSets), XML Infosets (LINQ to XML), and business entities created by the ADO.NET Entity Framework. The relative ease with which developers can write LINQ data providers has spawned a cottage industry of independent programmers who write LINQ data providers for recreation, demonstrations, presentations, or simply to demonstrate their C# chops.
You construct LINQ queries over .NET collections with statements composed of C# 3.0 or VB 9.0 keywords (called LINQ Standard Query Operators - SQO - sor standard sequence operators), many of which have corresponding or similar SQL reserved words. The System.Linq namespace''s Enumerable class defines the standard query operators. The .NET C# 3.0 and VB 9.0 compilers transform the query statements to the Common Language Runtime''s (CLR''s) intermediate language (IL) for execution. Therefore, the LINQ programming model is a first-class member of the .NET 3.5 Framework; it is not an add-in.
Here''s the general form of a basic LINQ query, as defined by Visual Studio 2008''s statement completion feature:
C# 3.0
var query = from element in collection[, from element2 in collection2]
where condition _
orderby orderExpression [ascending|descending][, orderExpression2 ...]
select [alias = ]columnExpression[,[alias2 = ]columnExpression2]
VB 9.0
Dim Query = From Element In Collection[,Element2 In Collection2] _
Where Condition _
Order By OrderExpression [Ascending|Descending][, _ OrderExpression2 ...] _
Select [Alias = ]ColumnExpression[,[Alias2 = ]ColumnExpression2]
This book uses C# lower-case and VB PascalCase interchangeably, except where keywords differ between the two languages, such as orderby and Order By in the preceding example. Preference is give to PascalCase to emphasize that the words are keywords.
The Dim and var keywords specify local variable type inference for the variable Query/query. Local variable type inference (LVTI) is a new C# 3.0/VB 9.0 language feature. VB''s new Option Infer {On|Off} statement controls LVTI, and the default for new projects is On, which enables LVTI with Option Strict On.
The preceding two examples correspond to this elementary SQL query syntax:
SQL
SELECT [Element.ColumnExpression[, Element2.ColumnExpression2]
FROM Collection AS Element[, Collection2 AS Element2]
WHERE Condition
ORDER BY OrderExpression [ASCENDING|DESCENDING][, OrderExpression2 ...]
The principal difference between LINQ and SQL queries is the position of the LINQ From clause, which determines the source of the data, at the start of the query. From before Select is necessary to enable IntelliSense. (SQL compilers perform this rearrangement before compiling the query.)
If you''re familiar with XQuery''s FLWOR (For, Let, Where, Order By, Return) syntax, you''ll notice the similarity of the keywords and clause sequences. XQuery''s for ... in keywords correspond to LINQ''s From ... In; C#''s LINQ implementation and XQuery use Let/let for variable assignment. XQuery''s return corresponds to LINQ''s Select.
LINQ, SQL, and XQuery are declarative programming languages. In contrast, C#, VB, Java, and Fortran are imperative languages. Declarative languages describe the programmer''s goal, while imperative programs describe a specific series of steps or algorithms to achieve the goal. LINQ''s use of a declarative query language enables the LINQ API and its extensions to optimize query processing at runtime in the same manner as SQL query optimizers.
You can query any information source that exposes the IEnumerable or IQueryable interface. Almost all .NET collections implement IEnumerable, which .NET 2.0 introduced. IQueryable is a new, enhanced version of IEnumerable that enables dynamic queries and other query features. Chapter 2 includes an introduction to the standard query operators, as well as the IEnumerable and IQueryable interfaces.
Third parties can create their own LINQ implementations by exposing the IEnumerable interface for their collection(s) with extension methods. Following in alphabetical order are some of the more imaginative third-party LINQ implementations that were available when this book was written: LINQ to Amazon by Fabrice Marguerie was the first generally available third-party LINQ provider. LINQ to Amazon returns lists of books meeting specific criteria.
LINQ to Expressions (MetaLinq) by Aaron Erickson (the developer of Indexes for Objects, i4o) lets you query over and edit expression trees with LINQ. Like .NET strings, LINQ expression trees are immutable; LINQ to Expressions changes a LINQ expression by making a copy, modifying the copy, and then replacing the original.
LINQ to Flickr by Mohammed Hossam El-Din uses the open-source FlickrNet C# library for digital images as its infrastructure.
LINQ to LDAP by Bart de Smet is a "query provider for LINQ that''s capable of talking to Active Directory (and other LDAP data sources potentially) over LDAP."
LINQ to NHibernate by Ayende Rahien (a.k.a. Oren Eini) translates LINQ queries to NHibernate Criteria Queries and was in the process of updating to .NET 3.5 when this book was written.
LINQ4SP by L&M Solutions of Hungary is an implementation of LINQ for SharePoint lists by an independent SharePoint specialist.
LINQ to Streams by Oren Novotny, this book''s technical editor, processes continuous data streams, such as stock tickers, network monitors, and sensor data.
Chapter 8 describes several of the preceding third-party LINQ flavors, and other Microsoft incubator implementations. The OakLeaf Systems blog provides a permanent, up-to-date list of third-party LINQ implementations at http://oakleafblog.blogspot.com/2007/03/third-partylinq-providers.html.
The LINQ standard query operators apply to all implementations, so developers don''t need to learn new query languages or dialects, such as SQL for relational databases, eSQL for the Entity Framework and EDM, XPath, or XQuery for XML Infosets, Lightweight Directory Access Protocol (LDAP) to query Active Directory and other LDAP-based directory systems, Collaborative Application Markup Language for SharePoint, and HibernateSQL (HSQL) for NHibernate.
The sections that follow briefly describe Microsoft''s LINQ implementations for the release version of Visual Studio 2008, which are illustrated by Figure 1-1. The ADO.NET team owns the LINQ to ADO.NET group members, which includes LINQ to Entities, LINQ to DataSets, and LINQ to SQL. The C# group owns the LINQ specification and LINQ to Objects, the ASP.NET team owns the LinqDataSource and EntityDataSource, and the XML Data Programmability team is responsible for LINQ to SQL and EF/ EDM. The XML team handles LINQ to XML and is indirectly responsible for LINQ to XSD.
The chapters of Part II, "Introducing Language Integrated Query," provides detailed coverage of extensions to the C# 3.0 and VB 9.0 languages to support LINQ and shows you the inner workings of LINQ to Objects. Part III, "Applying Domain-Specific LINQ Implementations," covers LINQ to SQL, the ASP.NET LinqDataSource, LINQ to DataSets, and LINQ to XML/LINQ to XSD. Chapter 12 explains the differences between LINQ to Entities and LINQ to SQL.
LINQ to Objects
LINQ to Objects is Microsoft''s default LINQ implantation, which is included in the .NET Framework 3.5''s System.Core.dll library. This means that it also is part of the Dynamic Language Runtime (DLR) that Microsoft announced at the MIX07 conference at the end of April 2007. The DLR release version will support JavaScript, IronPython, IronRuby, and the next VB version, VB 10.0 but currently called VBx. Silverlight 2 uses System.Core.dll to support LINQ and also supports LINQ to XML.
According to Paul Vick, the author of the VB.NET language specification, "Part of VBx is a hostable managed component (written in Visual Basic, no less!) built on top of the DLR. Since Silverlight can host DLR languages, this enables you to send Visual Basic code to a Silverlight instance and have it dynamically compiled and run." The XML Data Programmability team plans to support LINQ to XML in the DLR under Silverlight. VBx currently is the only DLR language that will support LINQ or LINQ to XML, but you can mix VBx source code with that of other dynamic languages.
(Continues...)
Excerpted from Professional ADO.NET 3.5 with LINQ and the Entity Frameworkby Roger Jennings Copyright © 2007 by Roger Jennings. Excerpted by permission.
All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.