Getting Started With LINQ 2009 by SupremeLord


									Increasing Your
with LINQ.....
  Rob Vettor

Rob Vettor                1

     Fly over @ 5,000 feet
     What it is
     What it does
     How it works
     Its value proposition
     Test drive examples
     Where to find out more

Rob Vettor                         2
                         Autobiographical Stuff…
   Architect/Team Lead
   C# MVP
   INETA Regional Speaker
   Frequent Presenter
   User Group Leader
   Developer Guidance Council member

Rob Ve                                             3

     How many use LINQ in production app?
     How many have looked at LINQ?
     How many use Visual Studio 2008?
     How many use Visual Studio 2008 and
        not LINQ?

Rob Vettor                                   4

     If you like presentation, please send email
     Lobby User Group Leader to have me
        present any of the following:
         – Getting Started with Entity Framework
         – Getting Started with Data Services
         – Advanced LINQ
         – Entity Framework 4.0
         – ADO.NET Data Services

Rob Vettor                                              5
Need for LINQ
LINQ to Objects
LINQ to SQL/Entities
LINQ Resources

Rob Vettor                   6
                                      Problem #1: Too Many APIs
       Different API‟s for performing identical data operations:
             – Querying collections
             – Querying databases
             – Querying XML
             – Querying ADO.NET structures
       Example: Find all customer with name of „Rob‟
       Different APIs, namespaces, classes, code constructs
       Need uniform approach for querying and manipulating
             data across different data sources

Rob Vettor                                                7
                         Problem #2: Database Mismatch
             Objects != Relational Data
 “Mismatch” (or incompatibility) between your data store and
    With OO, you traverse and manipulate objects
    With relational data, you join rows from tables
    Bridging gap time consuming and expensive:           Objects
     – Legacy ADO.NET
     – Hand-built DALs                  Relational Data

     – Wide assortment of 3rd party ORM Frameworks
    But, the core problem remains!

                                                This is Your Life
       You build applications for living
       Each talks to relational Database
       At the least, learn 2 different languages (C# and SQL)
             – Different syntax
             – Different type systems
             – Different tools
             – Different paradigms: Object vs. Procedural
       On top of that, must learn the API that binds these
             worlds together: ADO.NET
             – Powerful, but fragile and time-consuming

Rob Vettor                                                      9
                                      Common Pattern…

 using (SQLConnection conn = new SQLConnection(“<conn string>”);
   SQLCommand cmd = conn.CreateCommand();
   cmd.CommandText = “sp_StoredProc”;
   cmd.parameters.AddWithValue(“@City”, “Dallas”);
   using (SQLDataReader rdr = cmd.ExecuteReader())
     while (                   Parameters loosely bound: --
                                          Strings! No compile
                                          Names, types, number of
     {                                    Results are loosely typed
                                          time check until runtime
                                          not checkedor Intellisense
        string name = rdr.GetString(0);
        string city = rdr.GetString(1);
 }                 Integration story is weak!
Rob Vettor                                                    10
                                                  Enter LINQ

 Microsoft introduces LINQ…
      “Language INtegrated Query”
             – Unified query syntax across data sources
             – Bridges the gap between OO and Relation Data
             – Integrated directly into the language
             – Type checking and compile-time safety
             – Intellisense
             – Debugger support
      Higher productivity/lower heartburn

Rob Vettor                                                 11
                                  LINQ Components
  LINQ Query
                      C# 3.0         VB 9.0

                     LINQ to         LINQ to      LINQ to
                     Objects           SQL        Entities
LINQ Providers
                     LINQ to         LINQ to      LINQ to
                     DataSets          XML         REST

                      LINQ to        LINQ to       LINQ to
                       Excel       Sharepoint   Google Desktop

                      LINQ to       LINQ to         LINQ to
Rich Extensibility
                      MySQL         Streams     LDAP (Active Dir)

                      LINQ to      LINQ to          LINQ to
                     nHibernate    Amazon          JavaScript

      LINQ
             – Delivers uniform API for querying data
             – Addresses mismatch between data and objects
             – Type safety, intellisense and debugging support
             – Consists of providers and query operators
               integrated directly in language

Rob Vettor                                                  13

 Need for LINQ

LINQ to Objects…
 LINQ Resources

Rob Vettor               14
 Querying in-memory collections…
       Must be a collection
       Must implement IEnumerable<T> interface
             – Found in strongly-typed collections >= framework 2.0
             – Arrays
       For pre-2.0 collection, must cast to IEnumerable<T>:
             – ArrayLists
             – HashTables
             – Dictionaries

Rob Vettor                                                            15
 Interface that defines how to enumerate elements in a
  collection: MoveNext(), Current(), Reset()
 Implemented by both target and resultant collections in a
  LINQ Query:
    IEnumerable<T> query = from x in IEnumerable<T>
             select x;
 LINQ query operators (Where, Orderby, Select) require
  parameter of type IEnumerable<T>
 For LINQ-To-SQL and LINQ-To-Entities, must implement
  IQueryable<T>, which extends IEnumerable<T> by
  including expression tree concepts.

Rob Vettor                                           16
                                     LINQ to Objects
 Example with and without LINQ…
   Iterate thru collection of 77 products
   Filter out products less $20: With and Without LINQ
   Group by Category
   Order by Category descending
     1st example is imperative: Tell how; step-by-step
     2nd example is declarative: Tell what; LINQ determines
      how (like submitting a SQL statement to a DB)

Rob Vettor                                            17
                                           LINQ to Objects

 Examine key concepts that we just saw:
            Query operators
            Different types of query syntax
            Query processing order
            New language enhancements

Rob Vettor                                               18
                            Standard Query Operators
 Implemented across all LINQ providers as part of the language
       Operations     Operators
       Restriction    Where
       Projection     Select, SelectMany
       Ordering       OrderBy, ThenBy
       Grouping       GroupBy
       Joins          Join, GroupJoin
       Quantifiers    Any, All
       Partitioning   Take, Skip, TakeWhile, SkipWhile
       Sets           Distinct, Union, Intersect, Except
       Elements       First, Last, Single, ElementAt
       Aggregation    Count, Sum, Min, Max, Average
       Conversion     ToArray, ToList, ToDictionary
Rob Vettor                                                   19
                                      Writing LINQ Queries
        First way to write LINQ query: Query Expression
        Syntax that resembles a SQL Query
        Query Expression Structure:                    Source
         var query = from p in products
                   where p.unitPrice <= 20
Type               orderby p.unitPrice
Inference Result select p;
                Sequence              Projection      Range

    Query Pattern: Start with „from‟ and end with „select‟

   Rob Vettor                                                    20
                                     Query Processing Order
 How does SQL Server process this query internally?
            SELECT e.EmployeeID, c.FirstName, c.LastName
            FROM AS c
            INNERJOIN humanresources.employee as e
            ON c.ContactID = e.ContactID
            WHERE e.EmployeeID < 100
            ORDER BY c.LastName

            SELECT…………       [5]     Executed Last
            FROM…………… [ 1 ]          Executed First

            JOIN……………..      [3]     Executed First

            ON……………….        [2]     Executed First

            WHERE ………… [ 4 ]         Executed Next

            ORDER BY……... [ 6 ]      Executed Last

Rob Vettor                                                  21
                                                   Method Calls
 Second way to write LINQ queries: Method calls
 LINQ ships with 49 query operators, or extension methods, that
  perform querying operations: Joins, ordering, filtering, grouping,
  aggregation and projection.
             var query = products.Where(p => p.UnitPrice >= 20)
         .OrderBy(p =>p.ProductName)
         .Select(p => p.ProductName);
    Methods chained together to produce a pipeline effect for
      transforming data
    Note use of lambda expressions and how „p‟ effectively becomes a
      range variable, or alias, for the incoming sequence
    Query expressions and method calls

Rob Vettor                                                        22
                                             Anonymous Types
 Anonymous Type…
   Project strongly-typed result set without declaring type
   Relieves you from having to define concrete class for each type
    returned from a LINQ query
     – select new { … }
   Defines type inline                   curly braces
                                         no type name
 Type Inference…
     – Var name = "Hey“;  string name = "Hey";
     – Var age = 25;        int age = 25
   var keyword tells compiler to infer strong type based on right-side
   enforces strong typing (not a VB6 variant)                  No
DEMO                                                          type

 Have capability to combine values by joining multiple
  sequences, including inner and outer joins
 Also, LINQ queries are composable…
   Can combine and use one query as a building block for another
   Allows you to break complex problems into manageable pieces
             Demonstrate composability while joining 2 collections
 (Try doing this with a “for each” statement!)

Rob Vettor                                                  24
                                    What we have seen…
                 var contacts =                                Query
Type Inference
                   from c in customers                      Expressions
                   where c.State == "WA"
                   select new { c.Name, c.Phone };
                                     Operators         Lambda
                                   (Less-Friendly)   Expressions
                 var contacts =
                   .Where(c => c.State == "WA")
                   .Select(c => new { c.Name, c.Phone });


  Rob Vettor                                                       25

 Need for LINQ
 LINQ to Objects

 LINQ Resources

Rob Vettor               26
                                         LINQ to XML

 Framework 3.5 delivers new XML API:
   Named  LINQ to XML
   Lightweight and LINQ-friendly
   Makes it easy to create, parse and transform XML with
         LINQ syntax and special operators
      Includes XML DOM, integrates XPath and Xquery
      More Developer-Friendly–> Less string manipulation
      More Productive

Rob Vettor                                           27
                                    Programming XML Today

 This is your life…
  XmlDocument doc = new XmlDocument();
  XmlElement contacts = doc.CreateElement("contacts");
  foreach (Customer c in customers)
    if (c.Country == "USA") {                              Document
        XmlElement e = doc.CreateElement("contact");        centric
        XmlElement name = doc.CreateElement("name");
        name.InnerText = c.CompanyName;                    Brute-Force
        e.AppendChild(name);                                  String
        XmlElement phone = doc.CreateElement("phone");     Manipulation
        phone.InnerText = c.Phone;
                                                           Flat Structure
  doc.AppendChild(contacts);                    Memory
                                                   LINQ to XML
 How much work to join two external XML files together?
        Customer wants you to render CategoryName, not CategoryID
        To get CategoryName, would have to join the product and
         category XML files
 Next example…
        Open product and category xml file
        Implement LINQ query to transform each into a collection
        Use LINQ to join collections, filter on price and project data into


Rob Vettor                                                           29
                                                 LINQ to XML
 Create XML
        LINQ to XML goes beyond transforming XML
        Very easy to create XML with LINQ to XML
        Provides strongly-typed way to construct an XML Tree with the
         hierarchical relationships visually evident
        Code to create XML visually resembles the XML document
        Interestingly, document creation is a single statement


Rob Vettor                                                        30
                                      Mixing Data Sources

 Mixing Data Sources
        LINQ provides capability to simultaneously access different types
         of data sources with a single syntax in a single statement
 Next example…
        Load a collection of product objects
        Open a category xml file and load category objects
        Implement LINQ query to join the different collections into a single
         result set


Rob Vettor                                                         31
                                         LINQ to XML
 Up to this point…
        Can we all agree that
              LINQ to Objects
              LINQ to XML
        Good productivity tools?
        Simplify working with collections and XML?

Rob Vettor                                            32
                                     LINQ to SQL/EF
 Welcome to the Dark Side of LINQ
        Pushes query processing from in-memory
         out to a remote data store
        Delivers Visual ORM Tool to map relational
         data to object structures
        Automatically generates parameterized SQL
        Fully supports stored procedures

Rob Vettor                                            33
                                     Map Conceptual Model

 Designer Tour…
      With mapping wizard, create a new Entity Data Model
      Automatically generate 1-to1 mappings
      With EDMX Designer, examine entities, scalar and navigation
        Look at the Model Browser
        Look at the Mapping Details
        Look at the EDMX file
        Most importantly, look at generated entity classes
 End up with object-representation of our data store
Rob Vettor                                                    34
                                            Mapping Recap

          Relationship                              Represented by navigation
                     Scalar Property
                                Navigation Property Properties. Suppresses
   Object that describes an Pointer to related entity.
                      Value that is
   Association, denoted by Enable app to navigate       association entity
                  contained in the entity
  the multiplicity of endpoint      to and from.
 Key domain object
  distinguished by
     its identity

Rob Vettor                                                       35
                                 Simple Select Queries
 Simple LINQ-To-Entities Demo…
       Simple web form with GridView
       Simple “customers” entity
       Query all customers in Oregon
 Fire up SQL Profiler
 We are querying conceptual model, not store
 Demonstrate “Query Syntax” vs. “Method Syntax”

Rob Vettor                                          36
                           Key Concept: Object Context
     using (NorthwindEFEntities ctx = new NorthwindEFEntities())

– Workhouse of EF
  – Entry point to Entity Framework                         Object
  – Manages connection to data store                        Context

  – Generates SQL queries against store
  – Marshals data across boundaries and                     Entity
    materializes entity objects
  – Acts as local cache for storing the
    materialized objects                                 Target Entity

  – Maintains full change tracking and                 Uses factory to
    concurrency management                             Instantiate entity

 Rob Vettor                                                        37
                Associations/Navigation Properties

 When generating from database, EF infers <PK><FK>
  relationships and generates navigation properties
    Multiplicity
    Direction
 Navigate conceptual model
  without explicit joins
 Navigation properties, enable us
  to „dot‟ into related objects

 Rob Vettor                                      38
                                                          Navigation Properties
   – From Order, use navigation property to find related OrderDetail entities
                       from o in Order
                       where o.OrderDetails.unitPrice > 20
                       select o;
 OrderrID <pk>
                      Order maps reference to collection of Order Details objects (EntitySet Type)

       From OrderDetails, use navigation property to find Order entities

                       from d in OrderDetails
                       where d.Order.orderID == 1
 OrderDetail           select d;
 OrderD <fk>          Order Details maps reference to single Order object (EntityRef Type)


    Rob Vettor                                                                         39
                                                 Deferred Loading

   LINQ is built on concept of “deferred execution”
     Most query operators don‟t execute when declared
          – //-- First, define query
          –              var query = from c in ctx.Customers
                         where c.Region == "OR"
                         orderby c.CompanyName
Define query
 and store                select c;                         Execute query when
 in variable
                   //-- Then, execute query                  absolutely necessary
                   gvQuery.DataSource = query;
                   gvQuery.DataBind();
         Query gets executed when enumerated
               – Bound to a DataBound control
               – Execute within ForEach loop Iteration
               – Transformed to collection ToList(), ToArray(), etc

  Rob Vettor                                                           40
                                                            Eager Loading
 Force LINQ to immediately execute query
   Operators that return a singleton:
             – Aggregate Methods
             – Element Methods
             –    Retrieve specific element from sequence
             –    First(), Last(), ElementAt()
       Collection-Conversion Operators
             – ToArray(), ToList(), ToDictionary(), ToLookup()

 Include() method supports eager execution:
       Retrieves parent and child entities immediately, not when
 (No Demo Yet)

Rob Vettor                                                              41
                                 Loading Single Objects
 Basic Example
             – Run SQL Profiler and step thru code
             – Demonstrate Deferred and Eager loading
             – Explore when execution takes place
             – See how each enumeration of same query
               generates a separate call to DB


Rob Vettor                                              42
                                 Loading Object Graphs
 Object Graph: Set of individual, but related objects, that
  together form a logical whole unit

    Customer        Order   Order Detail   Product   Category

 By default, with deferred execution, child objects load one
  at a time (separate data store call for each) as needed.
 We can use Include() method to predefine the object graph,
  forcing all entire graph to load at once with single query
   Load object graph including Orders, Order Details
             and Products
Rob Vettor                                                43
                                 Deferred vs. Immediate
    Deferred Execution
             – Fetches data only when needed, not all at once
             – Minimize network traffic, memory consumption and
               load on database
             – Great for when can but fetch objects as user
               requests them
             – Chatty Interface: Each request for child record
               invokes explicit database query

Rob Vettor                                                  44
                       Deferred vs. Immediate
    Immediate Execution
             – Singe query returns all data
             – Great if you know that you will need all data returned
             – Large amount of data returned, whether used or not.

Rob Vettor                                                   45
                                     Updates/Change Tracking
 ObjectContext automatically tracks changes to entities via
  the ObjectStateManager object
    Upon retrieval, caches original values
    Tracks any changes made to entities
    Dynamically constructs update/insert SQL statements
             – If not updating an entity, disable Change Tracking
               – ctx.Products.MergeOption = MergeOption.NoTracking;
 Next DEMO
   Demonstrate change tracking
   Update postal code and freight charge for an order
   Watch ObjectStateManager track both changes and original values
   See it generate parameterized SQL update statement
   Explicitly wrap in transaction

Rob Vettor                                                            46
  Inserting with EF is multi-step process
         Create new (disconnected) entity object and populate
         Attach new entity to the ObjectContext
         Call SaveChanges() to commit to database
  Next DEMO
         Show how ObjectContext leverages inferred
            Inserts both parent and child records in correct order
            Maintains foreign key relationship
            Automatically manages the identity values
         Show that ObjectContext automatically returns new identity key
          and assigns to new entity objects

Rob Vettor                                                       47
                                                      EF vs. LTS
 General consensus:
   LTS
    – Strongly typed LINQ access for rapid development against SQL
    – Support direct (1-to-1) mapping with some functionality limitations
    – Limited out-of-the box support for complex scenarios
   EF
    – Designed for larger enterprise applications
    – Enables complex mapping complex scenarios
    – More robust tools and designer
    – Supports various types of inheritance, many-to-many relationships
      and composite types
    – Supports provider independence

                                                     EF vs. LTS
         Category             LINQ to SQL          Entity Framework
            Model            domain model        conceptual data model

  Databases Supported        SQL server only              Many

Complexity/Learning Curve     simple to use          complex to use

                                                 slower development but
   Development Time         rapid development
                                                    more capabilities

          Mapping             Direct 1-to-1         Custom mapping

        Inheritance           hard to apply          simple to apply

           Support                 ?            $$$, resources, innovation

   Rob Vettor                                                          49

 Need for LINQ
 LINQ to Objects

LINQ Resources…

Rob Vettor               50
             LINQ Books

Rob Vettor            51
                         LINQ Webcasts

 Mike Taulty
   150 Screen Casts

     Anders Hejlsberg

Rob Vettor                           52


Rob Vettor                                       53

To top