Linq 1224887336792847 9
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Linq 1224887336792847 9

on

  • 1,474 views

 

Statistics

Views

Total Views
1,474
Views on SlideShare
1,474
Embed Views
0

Actions

Likes
0
Downloads
13
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Linq 1224887336792847 9 Presentation Transcript

  • 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". ~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 = "Bart" ; 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") );
    • 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") );
    • }
    • }
  • 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)
  • 60. Override Database (Last 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