language integrated query: an introduction - … · language integrated query: an introduction....
TRANSCRIPT
DamienGuard(BSc,MBCS)http://[email protected]
GuernseySoftwareDeveloperForumhttp://developers.org.gg
Language Integrated Query: An introduction
What is LINQ?
• LanguageIntegratedQuery
• Makequeryapartofthelanguage
• Componentof.NETFramework3.5
• NowshippingwithVisualStudio2008
Query without LINQ
• ObjectsusingloopsandcondiVonsforeach(Customer c in customers) if (c.Region == "UK") ...
• DatabasesusingSQLSELECT * FROM Customers WHERE Region='UK'
• XMLusingXPath/XQuery//Customers/Customer[@Region='UK']
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();
Query with LINQ
C#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
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)
Advantages
• UnifieddataaccessSinglesyntaxtolearnandremember
• StronglytypedCatcherrorsduringcompilaVon
• IntelliSensePromptforsyntaxanda]ributes
• Bindableresultsets
ArchitectureOthersC# VB.NET
.NETLanguageIntegratedQuery(LINQ)
LINQtoSQL
LINQtoObjects
LINQtoXML
LINQtoDatasets
LINQtoEnVVes
LINQdatasourceproviders
ADO.NETsupportforLINQ
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 Objects
• QueryanyIEnumerable<T>sourceIncludesarrays,List<T>,DicVonary...
• ManyusefuloperatorsavailableSum,Max,Min,DisVnct,Intersect,Union
• ExposeyourowndatawithIEnumerable<T>orIQueryable<T>
• Createoperatorsusingextensionmethods
LINQ operatorsAggregate Conversion Ordering ParVVoning Sets
AggregateAverageCountMaxMinSum
CastOfTypeToArrayToDictionaryToListToLookupToSequence
OrderByThenByDescendingReverse
SkipSkipWhileTakeTakeWhile
ConcatDistinctExceptIntersectUnion
andmanyothers
LINQ to SQL• Object‐relaVonalmapping
Recordsbecomestrongly‐typedobjects
• Datacontextisthecontrollermechanism
• Facilitatesupdate,delete&insert
• TranslatesLINQqueriesbehindthescenes
• Type,parameterandinjecVonsafe
Database mapping
• VS2008designerorSQLMetalcommand
• Maptables&fieldstoclasses&properVes
• GeneratesparValclasseswitha]ributes
• Eachrecordbecomesanobject
• Datacontextrepresentsthedatabase
• UVlisetables,viewsorstoredprocedures
Modifying objects
• UpdateSetobjectproperVes
• Deletecontext.Table.DeleteOnSubmit(object)
• Insertcontext.Table.InsertOnSubmit(object)
• Commitchangesbackcontext.SubmitChanges()
TransacVonal‐allornothing
Additional providers
• RelaVonaldataNHibernate,MySQL,Oracle,PostgreSQL
• WebservicesRDF,Flickr,Amazon,WebQueries
• CustomLDAP,GoogleDesktop,SharePoint,TerraServermaps
Future developments
• BlinqScaffoldwebUIforlist/view/updatepages
• PLINQParallelqueryprocessingovermanyCPUs
• SyncLINQ&ConVnuousLINQUpdatedresultsviaINoVfyCollecVonChanged
Limitations
LINQ• Onlydefinesquery,notupdateorcontext
LINQToSQL• MappingissetatcompileVme• Cannotmixmappedandunmapped
properVesinasinglequery• MicrosohSQLServer2000,2005only
.NET features used
.NETFramework2.0
• ParValclasses(mapping)
.NETFramework3.5
• Anonymoustypes(shaping)
• Extensionmethods(queryoperators)
• Typeinference(varkeyword)
• Lambdaexpressions(querysyntax)
Alternatives for .NET
• NHibernate
• CastleMonoRail/AcVveRecord
• SubSonic
• CodegeneraVontool+templatesCodeSmith,MyGeneraVon,LLBLGen/Pro+NetTiers,DooDads,rollyourown...
More information
• Officialsite‐msdn.microsoh.com/linq/
• Tutorials‐weblogs.asp.net/sco]gu/
• Screencasts‐Vnyurl.com/yusch
• ThispresentaVon&cheatsheetdamieng.com/blog/tag/linq