LINQ Introduction

  • View
    6

  • Download
    0

Embed Size (px)

Text of LINQ Introduction

  • Language Integrated Query: An introductionDamien Guard (BSc, MBCS)http://damieng.comdamien@envytech.co.ukGuernsey Software Developer Forumhttp://developers.org.gg

  • What is LINQ?Language Integrated QueryMake query a part of the languageComponent of .NET Framework 3.5Now shipping with Visual Studio 2008

    Key feature of C# 3.0 and VB 9

  • Query without LINQObjects using loops and conditionsforeach(Customer c in customers) if (c.Region == "UK") ...Databases using SQLSELECT * FROM Customers WHERE Region='UK'XML using XPath/XQuery//Customers/Customer[@Region='UK']

    This is the situation today, a different language for each technology.

  • ADO without LINQSqlConnection con = new SqlConnection(...);con.Open(); SqlCommand cmd = new SqlCommand( @"SELECT * FROM Customers WHERE c.Region = @Region", con);cmd.Parameters.AddWithValue("@Region", "UK"); DataReader dr = cmd.ExecuteReader(); while (dr.Read()) { string name = dr.GetString(dr.GetOrdinal("Name")); string phone = dr.GetString(dr.GetOrdinal("Phone")); DateTime date = dr.GetDateTime(3);}dr.Close();con.Close();

    Hard to write database-neutral SQL because of subtle variances in the parameters, escaping, types etc.

  • Query with LINQC#var myCustomers = from c in customers where c.Region == "UK" select c;VB.NETDim myCustomers = From c In customers _ Where c.Region = "UK" _ Select c

    This is the same query in LINQ. You'll notice that the syntax is similar to SQL but with the select last. This is to facilitate IntelliSense - it needs to know what you are selecting from before it can offer what is available within that selection.

  • More LINQ queries

    C#var goodCusts = (from c in db.Customers where c.PostCode.StartsWith("GY") orderby c.Sales descending select c).Skip(10).Take(10);VB.NETDim goodCusts = (From c In db.Customers _ Where c.PostCode.StartsWith("GY") _ Order By c.Sales Descending _ Select c).Skip(1).Take(10)

  • AdvantagesUnified data accessSingle syntax to learn and rememberStrongly typedCatch errors during compilationIntelliSensePrompt for syntax and attributesBindable result sets

  • Architecture

    OthersC#VB.NET.NET Language Integrated Query (LINQ)LINQto SQLLINQto ObjectsLINQto XMLLINQto DatasetsLINQto EntitiesLINQ data source providersADO.NET support for LINQ

  • LINQ to ObjectsC#int[] nums = new int[] {0,4,2,6,3,8,3,1};double average = nums.Take(6).Average();var above = from n in nums where n > average select n;VB.NETDim nums() As Integer = {0,4,2,6,3,8,3,1}Double average = nums.Take(6).Average()Dim above = From n In nums _ Where n > average _ Select n

  • LINQ to ObjectsQuery any IEnumerable sourceIncludes arrays, List, Dictionary...Many useful operators availableSum, Max, Min, Distinct, Intersect, UnionExpose your own data with IEnumerable or IQueryableCreate operators using extension methods

  • LINQ operators

    and many others

    AggregateConversionOrderingPartitioningSetsAggregate Average Count Max Min SumCast OfType ToArray ToDictionary ToList ToLookup ToSequenceOrderBy ThenBy Descending ReverseSkip SkipWhile Take TakeWhileConcat Distinct Except Intersect Union

  • LINQ to SQLObject-relational mappingRecords become strongly-typed objectsData context is the controller mechanismFacilitates update, delete & insertTranslates LINQ queries behind the scenesType, parameter and injection safe

  • Database mappingVS 2008 designer or SQLMetal commandMap tables & fields to classes & propertiesGenerates partial classes with attributesEach record becomes an objectData context represents the databaseUtilise tables, views or stored procedures

  • Modifying objectsUpdateSet object propertiesDeletecontext.Table.DeleteOnSubmit(object)Insertcontext.Table.InsertOnSubmit(object)Commit changes backcontext.SubmitChanges()Transactional - all or nothing

  • Demo of LINQ to SQL

  • Additional providersRelational dataNHibernate, MySQL, Oracle, PostgreSQLWeb servicesRDF, Flickr, Amazon, WebQueriesCustomLDAP, Google Desktop, SharePoint, TerraServer maps

  • Future developmentsBlinqScaffold web UI for list/view/update pagesPLINQParallel query processing over many CPUsSyncLINQ & Continuous LINQUpdated results via INotifyCollectionChanged

  • LimitationsLINQOnly defines query, not update or context

    LINQ To SQLMapping is set at compile timeCan not mix mapped and unmapped properties in a single queryMicrosoft SQL Server 2000, 2005 only

  • .NET features used.NET Framework 2.0Partial classes (mapping)

    .NET Framework 3.5Anonymous types (shaping)Extension methods (query operators)Type inference (var keyword)Lambda expressions (query syntax)

  • Alternatives for .NETNHibernateCastle MonoRail / ActiveRecordSubSonicCode generation tool + templatesCodeSmith, MyGeneration, LLBLGen/Pro +NetTiers, DooDads, roll your own...

  • More informationOfficial site - msdn.microsoft.com/linq/Tutorials - weblogs.asp.net/scottgu/Screencasts - tinyurl.com/yuscftThis presentation & cheat sheetdamieng.com/blog/tag/linq

  • Questions & answers

    Key feature of C# 3.0 and VB 9This is the situation today, a different language for each technology.Hard to write database-neutral SQL because of subtle variances in the parameters, escaping, types etc.This is the same query in LINQ. You'll notice that the syntax is similar to SQL but with the select last. This is to facilitate IntelliSense - it needs to know what you are selecting from before it can offer what is available within that selection.