Linq To The Enterprise


Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Linq To The Enterprise

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