Linq 2008
-
Upload
prithumit-deb -
Category
Documents
-
view
215 -
download
2
description
Transcript of Linq 2008
Linq 2010
Course Overview• Linq Foundation
– What is it?– Why do I need it?– What does it actually do?
• Linq Requirements• New .Net language Features
– Implicitly Typed Variables– Object Initializes– Anonymous Methods– Extension Methods– Lambda Expressions
Course Overview
• Linq Basic Examples• Linq To SQL• Linq To Dataset• Linq To XML
What is Linq?
• Language Integrated Query• Feature Set of Microsoft’s .Net Framework
– Extensions added to .Net 3.5– Adds functionality to C# and VB.Net
• Standardizes Data Retrieval• Makes Query part of the Native
Programming Language
Why do we need Linq?
• Accessing and Manipulating data is a Major part of Application Development and Operation
• And the problem Is…– Every Data Source is Manipulated differently
• TSQL• MySQL• XPath
– The Code is not part of the Application Language– No Intelligence, error detection etc.
Why do we need Linq?
• Provides a consistent Programming Model for use with any Object or Data Source– Syntax is the same regardless of the data
source– Concepts are similar across data source
• Once you learn how to use Linq to access SQL data, you know most of what you need to know to access XML data
• Linq standardizes Operations; Not File Structure
How Linq Works
Linq Implementations
• Linq To SQL Server– Provides access to SQL Server data stores– Without leaving the syntax of the developing
language– Without leaving the compile-time environment
• Linq To XML– Provides access to XML data– XPath-like navigation through descendants,
ancestors and siblings
Linq Implementations
• Linq to DataSet– Provides access to ADO.NET DataSets– Populated by non SQL Server data sources
• Linq To Objects– A new way to deal with Collections– Access Collection data via Direct query
instead of For-Each Loops
Linq Architecture
• Linq consists of three Main Components– Language Features– Linq Engine– Linq Data Providers
Linq Architecture
• Linq Language Features– Query syntax– Implicitly types variables– Anonymous Methods– Object Initializers– Extension Methods– Lambda Expressions
Linq Architecture• Linq Engine
– Decides what action to take based on the type of data being queried
• Creates execution plans and executes the plan if the data is:
– An Object that implements IEnumberable or IEnumerable(of type)
– Data is stored in memory
• Uses a Linq Data Provider if:– Data is not an Object stored in memory
Linq Architecture
• Linq Data Providers– Microsoft Providers
• Linq to Objects• Linq to DataSets (ADO.NET)• Linq to Entities• Linq to XML• Linq to SQL (MS SQL Server)
– Each engine provides its own query processing engine or translates the query into another from
Linq Requirements
• Linq requires the following references in the Project– System.Core– System.Xml.Linq– System.Data.Linq– System.Data.DataSetExtensions
Linq Requirements
• The following namespaces must be imported– System.Linq– System.Xml.Linq– System.Data.Linq
• Visual Basic Compiler requirement– Type Inference must be set on– Option Infer On
Linq to Reality
• Linq is a tool; Not a Silver Bullet• Linq provides Consistency and simplicity• Linq can Introduce Performance problems
– Test Linq solutions against current solutions– www.microsoft.com
• Linq can Introduce Security Issues– www.microsoft.com
Linq Requirements
• Linq is part of Microsoft. Net Framework 4.0
• Visual Studio 2010• Language Choice
1. C#2. VB. Net
• Working with Linq in Visual Studio 2005– Possible, not recommended
New Features In C# and VB. Net
• .Net Framework 4.0– VB. Net 10.0– C# 4.0– Both full Support for Linq– Equally Linq capable
• Linq Functionality required New Language Constructs
New Features In C# and VB. Net
• New Language Features that Enable Linq– Query Syntax– Implicitly types variables– Anonymous types– Object initializers– Extension methods– Lambda expressions
Implicitly Types Variables• Declare Variables without specifying their type.
– variables are still strongly types; not variant– Compiler determines type based on the initialized
value– VS IDE uses the same algorithm to determine type
• Accurate predicts what the compiler will choose• Allows Intellisence functionality
• Type inference is always to the most general– Set a variable equal to 10/24/2010
• String, not date is chosen
Implicitly Types Variables
• Always declare the type if you know it• Implicit variables are ideally suited for Linq
and Anonymous types.
Implicitly Types Variables
• Demo
Object Initializers
• Constructor– Public Sub New() -> VB. Net– Public – same name as class
• OI’s perform same function as a constructor– Allows you to assign values to an objects fields or
properties when you create the object– You do not have to explicitly invoke a constructor
• Useful in ant context• Especially useful in Linq Query Expression
Object Initializers
• Demo
Anonymous Types
• Implicit type functionality for Objects– Set property values into an object without a
class definition– The resulting class has no usable name– The class name is generated by the compiler– The created class inherits from object– The result is an ‘anonymous’ type that is not
available at the source code level• Also called projections
Anonymous Types
• When to use Anonymous types– Need a temporary object to hold related data– Don’t need methods– If you need a different set of properties for
each declaration– If you need to change the order of the
properties for each declaration
Anonymous Types
• When not to use Anonymous types– When you need to define a method– When you need to define another variable– When you need to share data across methods
Anonymous Types
• Demo
Extension Methods
• Special kind of static method• Allow the addition of the methods to an existing
class outside the class definition– Without creating a new derived type– Without re-compiling or modifying the original type
• Called the same way regular methods are called• Marked with [Extension] attribute
– System.Runtime.CompilerServices• Called differently in C# and VB.Net
Extension Methods
• Demo
Lambda Expressions
• Anonymous Functions– A function without a name– Performs action and returns a single value– Can be used wherever a delegate type is valid
• Why?– Allow the function’s caller to define the action– Not just pass parameters
• Linq utilizes Lambda Expressions in the Select, Where, Order By calls
Lambda Expressions• Lambda in VB.Net
– Use the function keyword• Function(X) X+3 If X=1, then an integer of 4 is
returned• Function(X) X=5 If X=5, then boolean result of
true is returned• Function(X,Y) X+Y If X=2 & Y=4, the Integer 6 is
returned• Function(X,Y) X=Y If X=2 & Y=2, then boolean
true is returned
Lambda Expressions• Lambda In C#
– Use the lambda operator =>– Read as ‘goes to’
X=> X+3 If X=1, then an integer of 4 is returnedX=> X==5 If X=5, then boolean result of true is
returned(X,Y)=> X+Y If X=2 & Y=4, the Integer 6 is
returned(X,Y)=> X==y If X=2 & Y=2, then boolean true is
returned
Lambda Expressions
• Demo
Linq to SQL Basics
• Provides an ‘interface’ to SQL database– Represents database structure as objects
• DataContext Object– Manages communication and actions
between programming code and the actual database
– Maintains a connection string– Provides a number of functions
Linq to Sql Basics
• Linq to Sql object Mapping– Database maps to the Linq DataContext– Table maps to a class and collection– Views map to a class and collection– Columns map to properties of the Table class– Relationships map to a nested collection– Stored procedures map to class methods
Linq to Sql Basics
• Two ways to map database to Linq Objects– O/R designer in VS
• Drag and Drop• Creates objects automatically• Creates a .dbml file
– Manually program Linq Objects• Create a DataContext Object• Create a class for each Table• Create a property for each Column
Linq to XML
What About XML?
• Historically, .Net framework provides several techniques for working with XML– XmlDocument, XMLReader, XMLWriter, etc.
• Visual Studio 2008 (and .net framework 3.5) add a number of new techniques– A set of classes in the System.Xml.Linq namespace
• Makes it easier to generate and work with xml content
– Linq to XML• Standard, language-based mechanism to querying and
transforming xml content.
Visual Basic VS C#
• Both languages fully support System.Xml.Linq and Linq
• Visual Basic adds several features that simplify working with XML– XML literals– XML replacements– XML Axis Properties– And more
Creating XML Content
• Often, need to generate or modify XML content in code
• Start by reviewing “Old” techniques– Compare to new techniques
• Demos investigating– Using new XDocument, XElement and similar classes– Using XPath expressions to find specific nodes– Using new XML features to modify XML content
Creating XML using XMLDocument
• Most developers have used XMLDocument class to create a XML content– Works fine!– Problem: Its some what “Opaque”
• Need to create this simple XML:– Using XMLDocument, requires a bit of code
<?xml version=“1.0” encoding=“utf-8” standalone=“yes”><!– Sample customer information --><Customers/>
Creating XML using XMLDocument
• Each node requires a few steps:– Call a method on the root node to create a
new node– Append the child to an existing node
Creating XML Content using Linq
• XmlDocument makes it possible to create new content– Doesn’t make it easy– Each node requires aleast two lines of code
• .Net Framework 3.5 adds new set of classes in System.Xml.Linq namespace– XDocument, XElement, XAttribute, and so on
• Classes provides constructors that accepts arrays of Objects
• Demo introduces these classes– The basis for Linq over Xml
Traversing XML
• To search through xml, generally use XPath– Grammar of XML dedicated for searching
• .Net framework historically supported XPath– System.Xml.XPath namespace
• Linq doesn’t add new XPath features– Supplies bridge procedures allowing you to
access existing functionality
New Methods
• XPathSelectElements and XPathSelectElement methods– Allow you to supply an XPath expression– Methods return IEnumerable of XElement collection
or a single XElement instance• Methods are special:
– Extension methods ‘live’ in the System.Xml.XPath namespace
– Extend XElement, XDocument, XNode classes– Must import the System.Xml.XPath
Axis Methods
• Most developers view XML content as tree-based structure in memory
• Every node (except root node) can have a single parent– Multiple siblings, children, grandchildren, and so on
• Starting on any node, you can:– Up ( to parent – except for the root node)– Down ( to a child / grandchild)– Horizontally ( to a sibling)
Axis Methods• Each direction is called a axis• System.Xml.Linq namespace provides methods
to traverse axes• Subset includes:
– Ancestors, AncestorsAndSelf– Attribute, Attributes– Descendants– Element, Elements, ElementsAfterSelf,
EleemntsBeforeSelf– Parent
Updating XML Content
• Can use methods in System.Xml.Linq namespace to update XML content
• Add a child element: call XElement.Add• Remove an element: call XElement.Remove• Set a child element’s value:
XElementSetElementValue– Modify an existing element value– Create a new child element– Delete a child element
Verifying XML content with Schema
• System.Xml.Schema provides extension methods for XElement: validate
• Allows you to validate contents of XElement against schema
• Must import System.Xml.Schema namespace to use the method
• Validate method allows you to specify a SchemaCollection instance containing one or more schemas– Raises exception if it fails– Can also supply address of procedures to call if validation fails
• Must be a ValidationEventHandler delegate instance
Using Linq to query XML Content
• Pervious XML features only exist because of new Linq to XML querying features
• In order to support queries over XML– Linq needed new classes and features
• This section focuses on Linq Queries
Anonymous Type in Linq to XML
• In pervious demo, Linq query returned all the XML content– What if you want only a subset?
• Just as in any other Linq query– Can create anonymous type containing
subset of available data– You supply the structure, Linq does the rest.
Extension Methods
• Linq provides large number of extension methods– So you can perform calculations and conversion on
elements or groups of elements– All, Any, Average, Where, Concat, Contains– ConvertAll, Count, Distinct, Except– OrderBy, ThenBy, Select
• Demo uses Any method– Returns true if collection contains any elements
Lambda Expressions
• Pervious demo retrieved all customers who placed orders
• What if you want all customers who have placed any order that used Federal Shipping
• Any function can do it, but must calculate the subset– Use lambda expression to do the work
Linq to DataSet• DataSet
– In memory cache of data• Disconnected from data source
– Relational views of data• Contains tables, columns, rows, constraints, views and relationships
• Types Dataset are based on a schema and are strongly typed– Products.ProductName
• UnTyped Dataset don’t have a schema and are not strongly typed– Products(“ProductName”)
• Tables are represented by DataTable Class• Rows are represented by DataRow Class
Working with Data• You can use DataAdapater
– SqlDataAdapater for working with SQL Server– OledbDataAdapater for working with any data source
• You can use TableDataAdapater– Extends the functionality of DataAdapater– Can contain multiple queries
• Use the Fill method to fill a DataTable• Make changes in DataSet• Use the update method to write changes back to
data source
Linq to DataSet
• Easier way to query data in DataSet– Uses Linq query syntax
• Works with typed and untyped DataSets• Supports updating data and data binding• Linq queries are translated to .net
intermediate language since DataSet is in memory– No round trip to database server
Querying with Linq to DataSet
• First you need to retrieve data and populate DataTables– Data can come from database, xml, objects– Use code, Linq to XML, DataAdapater,
TableAdapater• Then write Linq queries to query
DataTables
Querying Untyped DataSet• DataTable class does not implement
IEnumerable• Use DataTables AsEnumerable extension
method• Use Generic Field accessor to refer to columns
in DataTable var query = from prod in products.AsEnumerable()
where prod.Field<Decimal>(“UnitPrice”) > 25M select new { ProductName = prod.Field<string>(“ProductName”) };
Querying typed DataSet
• Typed DataTables now inherits from genericTypedTableBass class, which implements IEnumerable– No need for AsEnumerable or generic Field
• Queries against typed DataSets are familiar Linq Syntax
var query = from prod in products where prod.UnitPrice > 25M select new { prod.ProductName };