linq 1224887336792847 9

69
Daniel N. Egan Microsoft Regional Director – California Microsoft MVP – ASP.Net Partner/Chief Architect - Odyssey Consulting Group

Upload: google

Post on 10-May-2015

1.416 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Linq 1224887336792847 9

Daniel N. EganMicrosoft Regional Director – California

Microsoft MVP – ASP.NetPartner/Chief Architect - Odyssey Consulting Group

Page 2: Linq 1224887336792847 9

Daniel EganDaniel Egan MCSD, MCSD, Microsoft Regional DirectorMicrosoft Regional Director

Microsoft MVP – ASP.NetMicrosoft MVP – ASP.Net MCSD, MCTMCSD, MCT

[email protected] INETA PresidentINETA President INETA Speakers BureauINETA 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

Page 3: Linq 1224887336792847 9

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.

Page 4: Linq 1224887336792847 9

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

Page 5: Linq 1224887336792847 9

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

Page 6: Linq 1224887336792847 9
Page 7: Linq 1224887336792847 9

“Object/relational mapping is the Vietnam of Computer Science". ~Ted Neward (http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx)

Page 8: Linq 1224887336792847 9

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

Page 9: Linq 1224887336792847 9
Page 10: Linq 1224887336792847 9

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

Page 11: Linq 1224887336792847 9

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

Page 12: Linq 1224887336792847 9

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

Page 13: Linq 1224887336792847 9

Examples◦ LLBLGen Pro◦ Wilson ORMapper ◦ CodeSmith◦ MyGeneration◦ Codus

Page 14: Linq 1224887336792847 9

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

Page 15: Linq 1224887336792847 9

Examples◦ Gentle.NET ◦ Linq to SQL (Dlink)(Demo)

Page 16: Linq 1224887336792847 9

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

Page 17: Linq 1224887336792847 9

Examples◦ NHibernate ◦ Linq to SQL (Dlinq)◦ Wilson ORMapper

Page 18: Linq 1224887336792847 9
Page 19: Linq 1224887336792847 9

“Language is the source of misunderstandings.”~Antoine de Saint-Exupery (1900 - 1944)

Page 20: Linq 1224887336792847 9

You are probably used to the normal syntax for writing property Getters – Setters.

Page 21: Linq 1224887336792847 9

Automatic Properties allow you to do the following

Benefit? Problem? What about

VB.Net?

Page 22: Linq 1224887336792847 9

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 }

Page 23: Linq 1224887336792847 9

Object Initializers allow you to initialize your objects without using the constructor.

Page 24: Linq 1224887336792847 9

Collection Initializers allow you to easily give values to collections in a rather concise and compact manner.

OLD Way

New Way

Page 25: Linq 1224887336792847 9

Extension Methods are Static/Shared methods marked with custom attributes that allow them to be invoked like an instance method.

OLD Way

With Extensions

Page 26: Linq 1224887336792847 9

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)

Page 27: Linq 1224887336792847 9

In a nut-shell, partial methods are a light-weight replacement for events designed primarily for use by automatic code generators.

Page 28: Linq 1224887336792847 9

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

Page 29: Linq 1224887336792847 9

Implicitly Declare means “no declared type”

VB.Net

C#

Page 30: Linq 1224887336792847 9

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 TYPEDAssigning a different type after initial declaration will cause

and error.

Page 31: Linq 1224887336792847 9

Anonymous Types allow you to create classes on-the-fly.

Declaration

Created

Page 32: Linq 1224887336792847 9
Page 33: Linq 1224887336792847 9

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") );

}}

Page 34: Linq 1224887336792847 9

Expression bodyx => x + 1

Statement block bodyx => { 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

Page 35: Linq 1224887336792847 9

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

Page 36: Linq 1224887336792847 9
Page 37: Linq 1224887336792847 9

Let’s Take a 15 Minute Break

After the break we will start looking at Linq

Page 38: Linq 1224887336792847 9

“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 ;)

Page 39: Linq 1224887336792847 9

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

Page 40: Linq 1224887336792847 9

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

Page 41: Linq 1224887336792847 9

LINQ enabled data sourcesLINQ enabled data sources

LINQTo Objects

ObjectsObjects

LINQTo XML

<book> <title/> <author/> <price/></book>

<book> <title/> <author/> <price/></book>

XMXMLL

LINQ enabled ADO.NET

LINQTo DataSets

LINQTo SQL

LINQTo Entities

RelationRelationalal

Others…VB C#

.NET Language-Integrated Query

Page 42: Linq 1224887336792847 9

“Syntax, my lad. It has been restored to the highest place in the republic.”

~John Steinbeck

Page 43: Linq 1224887336792847 9

var query = dc.Recipes .Where(r => r.Title.Contains(“Chocolate”)) .Select(r => new{new{rr.Title, .Title, r.NumberOfServings})r.NumberOfServings});

Extension Extension methodsmethods

Lambda Lambda expressionsexpressions

Object Object initializersinitializersAnonymous Anonymous

typestypes

Implicitly Implicitly Declared Declared

Local Local VariablesVariables

Extension Extension methodsmethods

Page 44: Linq 1224887336792847 9

These work similarly to their SQL counterparts◦ Select◦ Where◦ OrderBy/ThenBy◦ OrderByDescending/ThenByDescending◦ GroupBy◦ Count◦ Sum/Min/Max/Average

Page 45: Linq 1224887336792847 9

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

Page 46: Linq 1224887336792847 9

A query can be nested inside another query to produce a 1-Many Collection

var q = from c in db.Customerswhere c.City == "London"select new {

c.CompanyName,c.Phone,OrderDates = (

from o in c.Ordersselect o.OrderDate).Take(5) };

foreach( var c in q ) {Console.WriteLine( c.CompanyName );foreach( od in c.OrderDates )

Console.WriteLine( od )}

Page 47: Linq 1224887336792847 9

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

Page 48: Linq 1224887336792847 9

Every syntactic query expression in C# begins with a "fromfrom" clause and ends with either a "selectselect" or "group" clause.  ◦ The "from" clause indicates what data you want to query.  ◦ The "select" 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:

Page 49: Linq 1224887336792847 9

If we query from a Database we use the same syntax. We will cover the DataContext soon

Page 50: Linq 1224887336792847 9

What goes on under the covers?

You write this :

Linq sends this to the database

Page 51: Linq 1224887336792847 9

What about complex queries? You write this :

Linq sends this to the database

Extension Extension methodsmethods

Page 52: Linq 1224887336792847 9

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

Page 53: Linq 1224887336792847 9

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

Page 54: Linq 1224887336792847 9
Page 55: Linq 1224887336792847 9

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

Page 56: Linq 1224887336792847 9

 [Table(Name = "Customer")]    public class Customer    {        private int _Id;        private string _Name;        private string _Phone;         [Column(Id = true, Name = "Id”)]        public int Id { get { return _Id; } set { _Id = value; } }         [Column(Name = "Name")]        public string Name { get { return _Name; } set { _Name =

value; } }         [Column(Name = "PhoneNumber")]        public string Phone { get { return _Phone; } set { _Phone =

value; } }    }

But doing this manually is not required.!

Page 57: Linq 1224887336792847 9

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

Page 58: Linq 1224887336792847 9

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

Page 59: Linq 1224887336792847 9

Retain Database Values (First In Wins)

Page 60: Linq 1224887336792847 9

Override Database (Last In Wins)

Page 61: Linq 1224887336792847 9

Merge with other Values (User one wins conflicts)

Page 62: Linq 1224887336792847 9

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

Page 63: Linq 1224887336792847 9

Linq to Amazon Linq to Google Linq to Oracle Linq to You build your own provider

Page 64: Linq 1224887336792847 9
Page 65: Linq 1224887336792847 9

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.

Page 66: Linq 1224887336792847 9

Please fill out your Evaluations ;)

Page 67: Linq 1224887336792847 9
Page 68: Linq 1224887336792847 9

Query Controller Binding Flatten

Mapping Mapping

RewriteSQL2000

ParametersFlatten

Parameters

Readers

Format

Page 69: Linq 1224887336792847 9

DataContext

SubmitChange

Processor

Walk Objects

TX

Sequence

Do the Update

Dynamic

UserOverride