SlideShare a Scribd company logo
Daniel N. Egan Microsoft Regional Director – California Microsoft MVP – ASP.Net Partner/Chief Architect - Odyssey Consulting Group
Daniel Egan  MCSD,  Microsoft Regional Director Microsoft MVP – ASP.Net MCSD, MCT [email_address] INETA President INETA Speakers Bureau President Chief Architect for OCG Author : Building Websites with VB.Net and DotNetNuke 3.0  Packt Publishing .Net Certificate Instructor  California State University Fullerton CSUF .Net Advisory Board Member Run DotNetDoc.com Co-Founder – SoCalDotNet Southern California .Net Developers group.  http://www.SoCalDotNet.org http://www.LaCSharp.org
Understand the role of Object Relational Mappers A solid fundamental knowledge of then new language extensions for VB 9.0 and C# 3.0 A good understanding of Linq and specifically what Linq to SQL can do for you. How and where Linq should be used.
Object Relational Mappers C# and VB.Net Language Enhancements Automatic Properties Object Initializers Collection Initializers Extension Methods Partial Methods Anonymous types/ Implicitly typed local variables Lambda Expressions Expression Trees
Linq Goals A Brief History of Linq Linq Fundamentals Query Syntax Hands On Linq to SQL Creating  and exploring a Linq to SQL DataModel Query Products from the Database Update a Product from the Database Updating Composed Objects Inserting Into the database Deleting From the database Using a stored procedure Concurrency SQLMetal and XML Mapping Linq Change Tracking Service Debugging  Linq to SQL Debug Visualizer
 
“ Object/relational mapping is the Vietnam of Computer Science".  ~Ted Neward  (http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx)
ORM addresses the “impedance  mismatch ” Databases – focus on rows, indexes and key-based relationships Objects – focus on object graphs, inheritance / polymorphism and property / object-based relationships Databases and Objects do not cleanly align
 
What are the advantages of ORM? Can radically reduce the amount of code you need to write (-30% compared to ADO.Net is not unusual)  Boost in productivity  Makes the application easier to maintain  Fosters thinking about an OO model compared to the more procedural SQL approach  What are the disadvantages?   Some loss of control over the persistence process  May be more difficult to tune queries  Can get unruly
Support for: All types of relationships (1-1, 1-n, n-n) Transactions Map single object to multiple tables and vice versa Object inheritance Object caching Optimized queries Smart updates Bulk inserts / updates Performance savvy queries / loading of object graphs Lazy Loading Support for multiple RDBMSs Load-time validation GUI for management
Code Generation focuses on generating all mappings and code at design-time Pros Avoids black box Often provides ability to modify / extend generations Everything is packaged together Normally provides GUI Quickly up and running Cons Less flexible – changes require regeneration Difficult to provide more complex ORM features Tied to specific patterns / constructs Can bloat projects
Examples LLBLGen Pro Wilson ORMapper  CodeSmith MyGeneration Codus
Attributes allow you to map objects to databases within your code Pros Everything is packaged together Relationships are readily apparent to coder Compile-time validation (limited) Cons Tightly coupled framework Unable to modify mappings without modifying code and recompiling Bloats code
Examples Gentle.NET  Linq to SQL (Dlink)(Demo)
XML mappings allow you to define object to database mappings via an external XML file Pros Allows for run-time modification Can be coupled w/ code generation to speed development Easier to extend / provide frameworks on top of Loosely coupled Cons Requires packaging of external files No compile-time validation More error-prone Syntax to learn if no GUI provided
Examples NHibernate  Linq to SQL (Dlinq) Wilson ORMapper
 
“ Language is the source of misunderstandings.” ~ Antoine de Saint-Exupery (1900 - 1944)
You are probably used to the normal syntax for writing property Getters – Setters.
Automatic Properties allow you to do the following Benefit? Problem? What about VB.Net?
1   using  System;  2   3   namespace  ConsoleApplication1  4   {  5   class  Program  6   {  7   public   string  Name {  get ;  set ; }  8   9   static   void  Main( string [] args)  10  {  11  var p =  new  Program();  12  p.Name =  "Bart" ;  13  }  14  }  15   }
Object Initializers allow you to  initialize your objects without using the constructor.
Collection Initializers allow you to easily give values to collections in a rather concise and compact manner. OLD Way New Way
Extension Methods are Static/Shared methods marked with custom attributes that allow them to be invoked like an instance method. OLD Way With Extensions
Can you add Extensions to a Sealed Class? Yes Can you hide or override an existing method on a class? No Do Extension methods have direct access to the members of the type it is addressing? No (They are extending NOT inheriting) Only the FIRST parameter can be qualified with a this (or in VB the first is automatically used)
In a nut-shell, partial methods are a light-weight replacement for events designed primarily for use by automatic code generators.
Partial Methods can ONLY be defined within a partial class Partial Methods MUST return void (or a Sub in VB.Net) Partial Methods can be STATIC (Shared) or INSTANCE methods. Partial Methods CAN have arguments Partial Methods are always IMPLICITLY private
Implicitly Declare means “no declared type” VB.Net C#
Restrictions ONLY applies to local variables CANNOT be used for return variables MUST be assigned a value at time of declaration CANNOT be assigned a value of NULL ( can be assigned null after initial declaration) CAN also be used for Arrays  Implicitly typed local arrays var a = new[]{1,10,100,1000}; REMEMBER THESE ARE  STONGLY TYPED Assigning a different type after initial declaration will cause and error.
Anonymous Types allow you to create classes on-the-fly. Declaration Created
 
class LotsOfUppers { delegate string MyDelegate(string s);  private static string MyFunc(string s) {return s.ToUpper();} static void Main() { Console.WriteLine( MyFunc(“Calling a Function”); MyDelegate del; del = new MyDelegate( MyFunc ); Console.WriteLine( del(“Calling a .NET 1.0 Delegate") ); del = delegate( string s ) { return s.ToUpper(); };  Console.WriteLine( del(“Calling a .NET 2.0 Anonymous Method") ); del = s => s.ToUpper() ;  Console.WriteLine( del(“Calling a .NET 3.0 Lambda Expression") );  } }
Expression body x => x + 1 Statement block body x => { return x + 1; } Statement body can have arbitrarily many lines As of Beta 2 lambda expressions do not support statement bodies in lambdas. You must use .NET 2.0 anonymous methods instead. Only expression body lambdas can compile into expression trees
Or, lambda expression can be compiled to an expression tree An efficient in-memory data structure that makes the structure of the expression transparent and explicit  This allows the expression to be evaluated, copied and modified without using reflection DLINK uses expression trees to construct SQL statements that can execute on database server
 
Let’s Take a 15 Minute Break After the break we will start looking at Linq
“ It is a mistake to try to look too far ahead. The chain of destiny can only be grasped one  LINQ  at a time.” ~Sir Winston Churchill (1874 - 1965) – modified slightly  ;)
Linq has been over 7 years in the making ObjectSpaces PDC 2001 Supposed to be part of .Net 2.0 Linked to WinFS C – Omega  Researched by Erik Meijer and Worlfram Schulte Released as a preview in 2004 Language Extensions Worked a lot with XML, Streams, Anonymous Structs Linq Backed by Anders Hejlsberg  - Distinguished Engineer (Only 16 ever) – Chief Designer of C# Matt Warren – Chief Engineer Luca Bolognese– Lead Developer
Integrate Objects, Relational Data & XML SQL and Xquery-like power in C# and VB Extensible Model for languages Type Safety Extensive IntelliSense support Debugger Support Run on the .Net 2.0 CLR 100% backwards compatible
LINQ enabled data sources LINQ To Objects Objects LINQ To XML <book> <title/> <author/> <price/> </book> XML LINQ enabled ADO.NET LINQ To DataSets LINQ To SQL LINQ To Entities Relational Others… VB C# .NET Language-Integrated Query
“ Syntax, my lad. It has been restored to the highest place in the republic.” ~John Steinbeck
var  query = dc.Recipes .W here (r =>  r.Title.Contains( “Chocolate” ) ) .S elect (r =>   new{ r .Title, r.NumberOfServings}) ; Extension methods Lambda expressions Object initializers Anonymous types Implicitly Declared Local Variables Extension methods
These work similarly to their SQL counterparts Select Where OrderBy/ThenBy OrderByDescending/ThenByDescending GroupBy Count Sum/Min/Max/Average
Combine two sets of elements Union Returns all distinct elements in both sets Intersection Returns only elements belonging to both sets Except Returns elements in Set A but not in Set B Repeat Returns multiple copies of a set of elements Distinct Removes duplicate elements
A query can be nested inside another query to produce a 1-Many Collection var q = from c in db.Customers where c.City == &quot;London&quot; select new { c.CompanyName, c.Phone, OrderDates = ( from o in c.Orders select o.OrderDate) .Take(5) }; foreach( var c in q ) { Console.WriteLine( c.CompanyName ); foreach(  od in c.OrderDates ) Console.WriteLine( od ) }
Assigning a query to an IEnumerable<T> variable doesn’t execute the query When user iterates over members of the collection, each query operator executes as many times as needed to retrieve the next element Hence the data can change while elements are still being retrieved Use .ToList<T> or .ToArray<T> to force iteration over the entire query in one statement Creates a snapshot copy of the original data
Every syntactic query expression in C# begins with a &quot; from &quot; clause and ends with either a &quot; select &quot; or &quot; group &quot; clause.   The &quot; from &quot; clause indicates what data you want to query.   The &quot; select &quot; clause indicates what data you want returned, and what shape it should be in. For example, let's look again at the query against the List<Person> collection:
If we query from a Database we use the same syntax. We will cover the DataContext soon
What goes on under the covers? You write this : Linq sends this to the database
What about complex queries? You write this : Linq sends this to the database Extension methods
DataContext.Log =  DataContext.GetCommand(query).CommanText Query.ToString() Method SQL Server Query Visualizer  http://www.scottgu.com/blogposts/linqquery/SqlServerQueryVisualizer.zip Debugger Writer http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11
In C# 3.0, the IDE still doesn’t do background compilation, so it has to parse code line-by-line Putting SELECT before FROM would prevent IntelliSense from knowing what can be SELECTed
 
The DataContext Object is what links the class entities to the database entities. This can be done by hand OR by using the Linq to SQL Class Model
  [Table(Name = &quot;Customer&quot;)]      public class Customer      {          private int _Id;          private string _Name;          private string _Phone;             [Column(Id = true, Name = &quot;Id”)]          public int Id { get { return _Id; } set { _Id = value; } }            [Column(Name = &quot;Name&quot;)]          public string Name { get { return _Name; } set { _Name = value; } }            [Column(Name = &quot;PhoneNumber&quot;)]          public string Phone { get { return _Phone; } set { _Phone = value; } }      } But doing this manually is not required.!
Creating a Linq to SQL DataModel Query Products from the Database Update a Product from the Database Updating Composed Objects Inserting Into the database Deleting From the database Using a stored procedure Concurrency SQLMetal and XML Mapping Linq Change Tracking Service Debugging
Easiest  ResolveAll() Override With Current Values KeepCurrentValues KeepChages Easy  Resolve() Resolve Each conflict Individually with Items above Manual Loop through and write your own conflict resolution Using UpdateCheck Attribute Always Never When Changed Pessimistic can be done by wrapping it in a transaction
Retain Database Values  (First In Wins)
Override Database (Last In Wins)
Merge with other Values (User one wins conflicts)
Command line utility provided to automate creation of annotated entity classes to match a database schema SqlMetal /server:.\SQLExpress  /database:Northwind  /delayfetch  /pluralize  /namespace:nwind  /code:Northwind.cs
Linq to Amazon Linq to Google Linq to Oracle Linq to You build your own provider
 
Understand the role of Object Relational Mappers A solid fundamental knowledge of then new language extensions for VB 9.0 and C# 3.0 A good understanding of Linq and specifically what Linq to SQL can do for you. How and where Linq should be used.
Please fill out your Evaluations ;)
 
Query Controller Binding Flatten Mapping Mapping Rewrite SQL2000 Parameters Flatten Parameters Readers Format
Submit Data Context Change Processor Walk  Objects TX Sequence Do the Update Dynamic User Override

More Related Content

PPTX
Itinerary Website (Web Development Document)
PPTX
Real world DSL - making technical and business people speaking the same language
PDF
Annotations in PHP: They Exist
PPTX
Introduction to JAVA
PDF
Introduction to Clojure
PDF
Model-Driven Software Development - Language Workbenches & Syntax Definition
PPTX
JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Ann...
PPSX
Elements of Java Language
Itinerary Website (Web Development Document)
Real world DSL - making technical and business people speaking the same language
Annotations in PHP: They Exist
Introduction to JAVA
Introduction to Clojure
Model-Driven Software Development - Language Workbenches & Syntax Definition
JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Ann...
Elements of Java Language

What's hot (19)

PPTX
Core java
ZIP
Introduction to the Java(TM) Advanced Imaging API
PDF
Java Interview Questions
PPTX
JAVA PROGRAMMING
PPT
JavaClassPresentation
PPTX
Java Beans
PPTX
basic core java up to operator
PPTX
Object oriented programming-with_java
PPTX
PDF
Basic Java Programming
PPTX
Improving Software Quality Using Object Oriented Design Principles
PPTX
Introduction to java
PPTX
Object oriented concepts with java
PPTX
Core java online training
PDF
Java - OOPS and Java Basics
PPT
Java Basics
PDF
Smart Annotation Processing - Marseille JUG
PDF
F# and SignalR for a FastWeb
PPSX
Short notes of oop with java
Core java
Introduction to the Java(TM) Advanced Imaging API
Java Interview Questions
JAVA PROGRAMMING
JavaClassPresentation
Java Beans
basic core java up to operator
Object oriented programming-with_java
Basic Java Programming
Improving Software Quality Using Object Oriented Design Principles
Introduction to java
Object oriented concepts with java
Core java online training
Java - OOPS and Java Basics
Java Basics
Smart Annotation Processing - Marseille JUG
F# and SignalR for a FastWeb
Short notes of oop with java
Ad

Viewers also liked (10)

PPT
Linq 090701233237 Phpapp01
PPT
Linq E Ef 1207668728621762 9
PPT
Rolling Linq Wcf Silverlight Old4830
PPT
Linq 1207579553462901 8
PPT
Linq To Sql 1221970293242272 9
PPT
Introduccion A Linq 1205779028184546 5
PPTX
Linqtosql 090629035715 Phpapp01
PPTX
Cloud computing: highlights
PPT
Introduccion a LINQ
Linq 090701233237 Phpapp01
Linq E Ef 1207668728621762 9
Rolling Linq Wcf Silverlight Old4830
Linq 1207579553462901 8
Linq To Sql 1221970293242272 9
Introduccion A Linq 1205779028184546 5
Linqtosql 090629035715 Phpapp01
Cloud computing: highlights
Introduccion a LINQ
Ad

Similar to Linq 1224887336792847 9 (20)

PPT
Linq To The Enterprise
PPTX
Building nTier Applications with Entity Framework Services (Part 1)
PPT
Daniel Egan Msdn Tech Days Oc Day2
PPTX
Building nTier Applications with Entity Framework Services (Part 1)
PPTX
Framework engineering JCO 2011
PDF
Ruby On Rails
PDF
Dot Net Fundamentals
PPTX
Obevo Javasig.pptx
PPT
Smoothing Your Java with DSLs
DOCX
Patterns (contd)Software Development ProcessDesign patte.docx
PPTX
Entity Framework v1 and v2
PDF
Object- Relational Persistence in Smalltalk
PPTX
Framework Design Guidelines For Brussels Users Group
PDF
Working Effectively With Legacy Perl Code
PPT
What's New for Data?
PPTX
Implementing DDD with C#
PDF
TI1220 Lecture 14: Domain-Specific Languages
PPT
Object Oriented Concepts and Principles
PPTX
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
PDF
Entity Framework Interview Questions PDF By ScholarHat
Linq To The Enterprise
Building nTier Applications with Entity Framework Services (Part 1)
Daniel Egan Msdn Tech Days Oc Day2
Building nTier Applications with Entity Framework Services (Part 1)
Framework engineering JCO 2011
Ruby On Rails
Dot Net Fundamentals
Obevo Javasig.pptx
Smoothing Your Java with DSLs
Patterns (contd)Software Development ProcessDesign patte.docx
Entity Framework v1 and v2
Object- Relational Persistence in Smalltalk
Framework Design Guidelines For Brussels Users Group
Working Effectively With Legacy Perl Code
What's New for Data?
Implementing DDD with C#
TI1220 Lecture 14: Domain-Specific Languages
Object Oriented Concepts and Principles
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
Entity Framework Interview Questions PDF By ScholarHat

Recently uploaded (20)

PDF
Empathic Computing: Creating Shared Understanding
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPT
Teaching material agriculture food technology
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
MYSQL Presentation for SQL database connectivity
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Cloud computing and distributed systems.
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
Empathic Computing: Creating Shared Understanding
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
A Presentation on Artificial Intelligence
Advanced methodologies resolving dimensionality complications for autism neur...
Encapsulation_ Review paper, used for researhc scholars
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Teaching material agriculture food technology
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Building Integrated photovoltaic BIPV_UPV.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
MYSQL Presentation for SQL database connectivity
“AI and Expert System Decision Support & Business Intelligence Systems”
Understanding_Digital_Forensics_Presentation.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Cloud computing and distributed systems.
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
20250228 LYD VKU AI Blended-Learning.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf

Linq 1224887336792847 9

  • 1. Daniel N. Egan Microsoft Regional Director – California Microsoft MVP – ASP.Net Partner/Chief Architect - Odyssey Consulting Group
  • 2. Daniel Egan MCSD, Microsoft Regional Director Microsoft MVP – ASP.Net MCSD, MCT [email_address] INETA President INETA Speakers Bureau President Chief Architect for OCG Author : Building Websites with VB.Net and DotNetNuke 3.0 Packt Publishing .Net Certificate Instructor California State University Fullerton CSUF .Net Advisory Board Member Run DotNetDoc.com Co-Founder – SoCalDotNet Southern California .Net Developers group. http://www.SoCalDotNet.org http://www.LaCSharp.org
  • 3. Understand the role of Object Relational Mappers A solid fundamental knowledge of then new language extensions for VB 9.0 and C# 3.0 A good understanding of Linq and specifically what Linq to SQL can do for you. How and where Linq should be used.
  • 4. Object Relational Mappers C# and VB.Net Language Enhancements Automatic Properties Object Initializers Collection Initializers Extension Methods Partial Methods Anonymous types/ Implicitly typed local variables Lambda Expressions Expression Trees
  • 5. Linq Goals A Brief History of Linq Linq Fundamentals Query Syntax Hands On Linq to SQL Creating and exploring a Linq to SQL DataModel Query Products from the Database Update a Product from the Database Updating Composed Objects Inserting Into the database Deleting From the database Using a stored procedure Concurrency SQLMetal and XML Mapping Linq Change Tracking Service Debugging Linq to SQL Debug Visualizer
  • 6.  
  • 7. “ Object/relational mapping is the Vietnam of Computer Science&quot;. ~Ted Neward (http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx)
  • 8. ORM addresses the “impedance mismatch ” Databases – focus on rows, indexes and key-based relationships Objects – focus on object graphs, inheritance / polymorphism and property / object-based relationships Databases and Objects do not cleanly align
  • 9.  
  • 10. What are the advantages of ORM? Can radically reduce the amount of code you need to write (-30% compared to ADO.Net is not unusual) Boost in productivity Makes the application easier to maintain Fosters thinking about an OO model compared to the more procedural SQL approach What are the disadvantages? Some loss of control over the persistence process May be more difficult to tune queries Can get unruly
  • 11. Support for: All types of relationships (1-1, 1-n, n-n) Transactions Map single object to multiple tables and vice versa Object inheritance Object caching Optimized queries Smart updates Bulk inserts / updates Performance savvy queries / loading of object graphs Lazy Loading Support for multiple RDBMSs Load-time validation GUI for management
  • 12. Code Generation focuses on generating all mappings and code at design-time Pros Avoids black box Often provides ability to modify / extend generations Everything is packaged together Normally provides GUI Quickly up and running Cons Less flexible – changes require regeneration Difficult to provide more complex ORM features Tied to specific patterns / constructs Can bloat projects
  • 13. Examples LLBLGen Pro Wilson ORMapper CodeSmith MyGeneration Codus
  • 14. Attributes allow you to map objects to databases within your code Pros Everything is packaged together Relationships are readily apparent to coder Compile-time validation (limited) Cons Tightly coupled framework Unable to modify mappings without modifying code and recompiling Bloats code
  • 15. Examples Gentle.NET Linq to SQL (Dlink)(Demo)
  • 16. XML mappings allow you to define object to database mappings via an external XML file Pros Allows for run-time modification Can be coupled w/ code generation to speed development Easier to extend / provide frameworks on top of Loosely coupled Cons Requires packaging of external files No compile-time validation More error-prone Syntax to learn if no GUI provided
  • 17. Examples NHibernate Linq to SQL (Dlinq) Wilson ORMapper
  • 18.  
  • 19. “ Language is the source of misunderstandings.” ~ Antoine de Saint-Exupery (1900 - 1944)
  • 20. You are probably used to the normal syntax for writing property Getters – Setters.
  • 21. Automatic Properties allow you to do the following Benefit? Problem? What about VB.Net?
  • 22. 1 using System; 2 3 namespace ConsoleApplication1 4 { 5 class Program 6 { 7 public string Name { get ; set ; } 8 9 static void Main( string [] args) 10 { 11 var p = new Program(); 12 p.Name = &quot;Bart&quot; ; 13 } 14 } 15 }
  • 23. Object Initializers allow you to initialize your objects without using the constructor.
  • 24. Collection Initializers allow you to easily give values to collections in a rather concise and compact manner. OLD Way New Way
  • 25. Extension Methods are Static/Shared methods marked with custom attributes that allow them to be invoked like an instance method. OLD Way With Extensions
  • 26. Can you add Extensions to a Sealed Class? Yes Can you hide or override an existing method on a class? No Do Extension methods have direct access to the members of the type it is addressing? No (They are extending NOT inheriting) Only the FIRST parameter can be qualified with a this (or in VB the first is automatically used)
  • 27. In a nut-shell, partial methods are a light-weight replacement for events designed primarily for use by automatic code generators.
  • 28. Partial Methods can ONLY be defined within a partial class Partial Methods MUST return void (or a Sub in VB.Net) Partial Methods can be STATIC (Shared) or INSTANCE methods. Partial Methods CAN have arguments Partial Methods are always IMPLICITLY private
  • 29. Implicitly Declare means “no declared type” VB.Net C#
  • 30. Restrictions ONLY applies to local variables CANNOT be used for return variables MUST be assigned a value at time of declaration CANNOT be assigned a value of NULL ( can be assigned null after initial declaration) CAN also be used for Arrays Implicitly typed local arrays var a = new[]{1,10,100,1000}; REMEMBER THESE ARE STONGLY TYPED Assigning a different type after initial declaration will cause and error.
  • 31. Anonymous Types allow you to create classes on-the-fly. Declaration Created
  • 32.  
  • 33. class LotsOfUppers { delegate string MyDelegate(string s); private static string MyFunc(string s) {return s.ToUpper();} static void Main() { Console.WriteLine( MyFunc(“Calling a Function”); MyDelegate del; del = new MyDelegate( MyFunc ); Console.WriteLine( del(“Calling a .NET 1.0 Delegate&quot;) ); del = delegate( string s ) { return s.ToUpper(); }; Console.WriteLine( del(“Calling a .NET 2.0 Anonymous Method&quot;) ); del = s => s.ToUpper() ; Console.WriteLine( del(“Calling a .NET 3.0 Lambda Expression&quot;) ); } }
  • 34. Expression body x => x + 1 Statement block body x => { return x + 1; } Statement body can have arbitrarily many lines As of Beta 2 lambda expressions do not support statement bodies in lambdas. You must use .NET 2.0 anonymous methods instead. Only expression body lambdas can compile into expression trees
  • 35. Or, lambda expression can be compiled to an expression tree An efficient in-memory data structure that makes the structure of the expression transparent and explicit This allows the expression to be evaluated, copied and modified without using reflection DLINK uses expression trees to construct SQL statements that can execute on database server
  • 36.  
  • 37. Let’s Take a 15 Minute Break After the break we will start looking at Linq
  • 38. “ It is a mistake to try to look too far ahead. The chain of destiny can only be grasped one LINQ at a time.” ~Sir Winston Churchill (1874 - 1965) – modified slightly ;)
  • 39. Linq has been over 7 years in the making ObjectSpaces PDC 2001 Supposed to be part of .Net 2.0 Linked to WinFS C – Omega Researched by Erik Meijer and Worlfram Schulte Released as a preview in 2004 Language Extensions Worked a lot with XML, Streams, Anonymous Structs Linq Backed by Anders Hejlsberg - Distinguished Engineer (Only 16 ever) – Chief Designer of C# Matt Warren – Chief Engineer Luca Bolognese– Lead Developer
  • 40. Integrate Objects, Relational Data & XML SQL and Xquery-like power in C# and VB Extensible Model for languages Type Safety Extensive IntelliSense support Debugger Support Run on the .Net 2.0 CLR 100% backwards compatible
  • 41. LINQ enabled data sources LINQ To Objects Objects LINQ To XML <book> <title/> <author/> <price/> </book> XML LINQ enabled ADO.NET LINQ To DataSets LINQ To SQL LINQ To Entities Relational Others… VB C# .NET Language-Integrated Query
  • 42. “ Syntax, my lad. It has been restored to the highest place in the republic.” ~John Steinbeck
  • 43. var query = dc.Recipes .W here (r => r.Title.Contains( “Chocolate” ) ) .S elect (r => new{ r .Title, r.NumberOfServings}) ; Extension methods Lambda expressions Object initializers Anonymous types Implicitly Declared Local Variables Extension methods
  • 44. These work similarly to their SQL counterparts Select Where OrderBy/ThenBy OrderByDescending/ThenByDescending GroupBy Count Sum/Min/Max/Average
  • 45. Combine two sets of elements Union Returns all distinct elements in both sets Intersection Returns only elements belonging to both sets Except Returns elements in Set A but not in Set B Repeat Returns multiple copies of a set of elements Distinct Removes duplicate elements
  • 46. A query can be nested inside another query to produce a 1-Many Collection var q = from c in db.Customers where c.City == &quot;London&quot; select new { c.CompanyName, c.Phone, OrderDates = ( from o in c.Orders select o.OrderDate) .Take(5) }; foreach( var c in q ) { Console.WriteLine( c.CompanyName ); foreach( od in c.OrderDates ) Console.WriteLine( od ) }
  • 47. Assigning a query to an IEnumerable<T> variable doesn’t execute the query When user iterates over members of the collection, each query operator executes as many times as needed to retrieve the next element Hence the data can change while elements are still being retrieved Use .ToList<T> or .ToArray<T> to force iteration over the entire query in one statement Creates a snapshot copy of the original data
  • 48. Every syntactic query expression in C# begins with a &quot; from &quot; clause and ends with either a &quot; select &quot; or &quot; group &quot; clause.  The &quot; from &quot; clause indicates what data you want to query.  The &quot; select &quot; clause indicates what data you want returned, and what shape it should be in. For example, let's look again at the query against the List<Person> collection:
  • 49. If we query from a Database we use the same syntax. We will cover the DataContext soon
  • 50. What goes on under the covers? You write this : Linq sends this to the database
  • 51. What about complex queries? You write this : Linq sends this to the database Extension methods
  • 52. DataContext.Log = DataContext.GetCommand(query).CommanText Query.ToString() Method SQL Server Query Visualizer http://www.scottgu.com/blogposts/linqquery/SqlServerQueryVisualizer.zip Debugger Writer http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11
  • 53. In C# 3.0, the IDE still doesn’t do background compilation, so it has to parse code line-by-line Putting SELECT before FROM would prevent IntelliSense from knowing what can be SELECTed
  • 54.  
  • 55. The DataContext Object is what links the class entities to the database entities. This can be done by hand OR by using the Linq to SQL Class Model
  • 56.   [Table(Name = &quot;Customer&quot;)]     public class Customer     {         private int _Id;         private string _Name;         private string _Phone;            [Column(Id = true, Name = &quot;Id”)]         public int Id { get { return _Id; } set { _Id = value; } }           [Column(Name = &quot;Name&quot;)]         public string Name { get { return _Name; } set { _Name = value; } }           [Column(Name = &quot;PhoneNumber&quot;)]         public string Phone { get { return _Phone; } set { _Phone = value; } }     } But doing this manually is not required.!
  • 57. Creating a Linq to SQL DataModel Query Products from the Database Update a Product from the Database Updating Composed Objects Inserting Into the database Deleting From the database Using a stored procedure Concurrency SQLMetal and XML Mapping Linq Change Tracking Service Debugging
  • 58. Easiest ResolveAll() Override With Current Values KeepCurrentValues KeepChages Easy Resolve() Resolve Each conflict Individually with Items above Manual Loop through and write your own conflict resolution Using UpdateCheck Attribute Always Never When Changed Pessimistic can be done by wrapping it in a transaction
  • 59. Retain Database Values (First In Wins)
  • 61. Merge with other Values (User one wins conflicts)
  • 62. Command line utility provided to automate creation of annotated entity classes to match a database schema SqlMetal /server:.\SQLExpress /database:Northwind /delayfetch /pluralize /namespace:nwind /code:Northwind.cs
  • 63. Linq to Amazon Linq to Google Linq to Oracle Linq to You build your own provider
  • 64.  
  • 65. Understand the role of Object Relational Mappers A solid fundamental knowledge of then new language extensions for VB 9.0 and C# 3.0 A good understanding of Linq and specifically what Linq to SQL can do for you. How and where Linq should be used.
  • 66. Please fill out your Evaluations ;)
  • 67.  
  • 68. Query Controller Binding Flatten Mapping Mapping Rewrite SQL2000 Parameters Flatten Parameters Readers Format
  • 69. Submit Data Context Change Processor Walk Objects TX Sequence Do the Update Dynamic User Override