Applied Linq

  • View
    51

  • Download
    0

Embed Size (px)

DESCRIPTION

Applied Linq. Putting Linq to work. Introducing…. Class-A Kennisprovider Microsoft development Training Coaching http://www.class-a.nl Alex Thissen Trainer/coach http://blog.alexthissen.nl. Agenda. About Linq and queries Query providers and APIs What it means to apply Linq - PowerPoint PPT Presentation

Text of Applied Linq

  • Applied LinqPutting Linq to work

  • IntroducingClass-AKennisprovider Microsoft developmentTrainingCoachinghttp://www.class-a.nl

    Alex ThissenTrainer/coachhttp://blog.alexthissen.nl

  • AgendaAbout Linq and queriesQuery providers and APIsWhat it means to apply LinqLanguage and codeQuery executionRecommendationsArchitectureBeyond LinqDemosQuestions and discussion

  • Dim query = From c In customers _ Where c.Orders.Count > 100 _ Order By c.CompanyName Descending _ Select c Introducing LinqUniform way to write queries over dataLinq is about query keywordsBuilt into new languages C# 3.0 and VB 9.0Linq is about query operators40+ standard query operators are definedMethods that operate in queries or act on its results

    var query = from c in customers where c.Orders.Count > 100 orderby c.CompanyName descending select c;

  • About Linq queriesExpressed in terms of CLR typesObjects that might or might not exist in-memoryLinq queries are not SQL queries at allCompositional and hierarchical by natureArbitrary nesting of queriesAdditional operators can be applied to queryDeclarative instead of imperativeTell what you want, not howHow is up to underlying implementation

  • Writing queriesLearn the keywords and operatorsNot all operators have corresponding keywords or language integrationNumber of keywords may vary per languageSome parts must be written with operatorsUsually exposes lambda expressionsQueries can be done without keywordsExplicit dot notation (what compiler creates)Sometimes FLWOS is overkill

  • var query = from c in customers select c.Orders.Sum(o => o.Amount);var query2 = (from c in customers select c.Country).Distinct();Customer someCustomer = customers.FirstOrDefault(c => c.ID == 1337);Dim query = _ From c In customers _ Select c.Orders.Sum( _ Function (o As Order) o.Amount) _ )Dim query2 = From c In customers _ Select c.Country _ DistinctQuery samples* VB Lambda expressions will appear in Beta 2*

  • DemosGetting familiar with Linq queriesQuery operations: selection, projection, groupingUsing keywords and operators

  • Sources of dataYour data must come from somewhereIn-memory CLR objectsDatabaseXMLOther repositories: registry, Active Directory, Various flavors of Linq disclose certain type of dataQuery syntax does not change per sourceSet of keywords and operators available might be different

  • Linq to XMLPower of Linq brought to data in XML formatPerform queries over XML dataNew element-centric API to manipulate XMLFaster alternative to System.Xml DOM APIFunctional construction of XML data with query expressions

  • Linq to SQLGenerates object model to represent dataMapping of CLR types to database tablesObject/Relational Mapping (OR/M) technology1:1 relationships between objects and tablesTranslates Linq queries to SQL statementsBuilds on ADO.NET and .NET TransactionsPersistence servicesAutomatic change tracking and identity management of objectsUpdates by SQL statements or stored procedures

  • Mapping strategy

    Relationships map to collection propertiesSingle table inheritance is supportedData contextCustomer objectOrder objects

  • Two kinds of Linq

    Enumerable typesQueryable typesExecutionLocal in-memoryUsually remoteImplementationIterators using yield returnExpression tree parsingInterfaceIEnumerableIQueryableProvidersLinq to ObjectsLinq to SQL Entities (after 3.5)Other APIsLinq to XML DataSets

  • Query providersOut-of-the-box providers in .NET 3.5:Linq to ObjectsLinq to SQLSources in query determine query providersAffects keywords and operators you can useQuery providers can translate Linq queries to some implementationMost providers come with Linq-enabled APIsNew object models to work with dataLinq to Objects has several: Linq to XML, DataSets

  • DemoLinq applied

    Scenario: WCF services using untyped MessagesWPF ApplicationWCF ServiceWCF proxySOAP messagesLinq to XML APILinq to SQLLinq to XML

  • New language features C# and VBLinq keywordsExtension methodsLambda expressionsLocal variable inferenceObject and collection initializersAnonymous types

    Automatic propertiesPartial methods

    newnew

  • Visual Basic 9.0Deep XML supportExpress XPath axes with XML properties

    Allows XML literals to appear inside of code

    root. Direct child elements customer.@CompanyID Attribute selection doc... All descendantsDim fragment As XElement = _ Hedel

  • Visual Basic 9.0Gives you expression holes inside XML literals

    Additional keywordsMore freedom on order of keywordsDim query = _ From c In doc... _ Select phone:

  • DemoVisual Basic WCF sample revisitedDeep XML support

  • Deferred executionMost Linq query providers are implemented using lazy evaluationComposed query expressions do not execute immediatelyQueries only execute when necessaryPerforming an iteration over resultsetUsing extension methods ToArray, ToList, ToLookup, ToDictionaryUsing specific query operators, such as aggregates and set operators

  • More on deferred executionBefore execution queries can still be changed or expandedAdding additional sequence operators, such as Distinct, Skip, TakeManipulating expression treeExpression trees are immutableReference assignments take deep tree copies

  • Changes to way you write codeDeclarativeFar less looping constructs visibleEasier to read and to maintainMethods returning query or its resultsRemember deferred executionForce execution of queryHand over query for further manipulationQuery reuse

  • Linq and architectureSystem.Data.Linq

  • Architecture recommendationsFind out where and how your queries executeMoment of executionLocal versus remote executionPhysical place/tier of query executionKeep queries inside assembliesDo not pass query expressions between layersAnonymous types shouldnt be return valuesThink about important types up frontUse projections wisely

  • Other recommendationsLearn:to write queries with and without keywordsnew language featuresUse whitepapers as referenceTranslation of query keywords to operatorsEvaluation details of operatorsDo not overuse or abuse var keywordDecreases readability and stops you from thinking: if you know exact type, specify itIt sometimes takes more keystrokes

  • Runtimes and frameworks for LinqprovidersAPIs* ADO.NET Entity Framework released out of bounds with .NET FX 3.5*

    Linq to.NET FX 3.5Compact FX 3.5Silverlight 1.1ObjectsXXXSQLXEntitiesX

    DataSetsXXXMLXXX

  • Beyond .NET FX 3.5ADO.NET Entity Framework Microsofts long-term vision on dataBrings query provider Linq to EntitiesParallel Linq (PLinq)Passes parts of query to different cores in multicore/multiproc machineCommunity query providers for Linq:Linq to Amazon, LDAP, SharePoint, NHibernate, MySql, Flickr, and more (to come)Linq 2.0

  • Expanding on LinqLinq-enable your existing APIsSpecifically for in-memory queriesCreate extension methods that return an IEnumerable object Write your own query providerImplement IQueryableParse expression trees and translate nodes to different code or query language

  • ReferencesLinq home pageFuture versions of C#, Visual Basic, Visual StudioRecommended readingLinq to XML beta 1 docsFuture: Linq 2.0, PLinqDownloadsLinq May 2006 CTP (for Visual Studio 2005)Visual Studio Orcas April 2007 Beta 1 and C#, VB samplesReflector 5.0

  • BlogsMicrosoft TeamsC#VBADO.NETIndividuals on LinqGeneral: Oakleaf Systems, Wes Dyer, Jomo FisherSQL: Mike TaultyXML: Eric White

  • SummaryLinq is about query keywords and operatorsLinq will change way you write your codeLinq to XML might be more important than you thinkIs VB a better query language than C#?Linq is extensible

  • Questions??

    *Gevoel krijgen voor Linq en het toegepast zienEerste aanzet voor aanbevelingen en architectuur*Not SQL:Similar keywords for familiarityDifferent order for practical purposes and different execution

    Comprehensions allow query declaration left-to-right instead of inside out

    ***************************