Linq 1224887336792847 9

Post on 10-May-2015

1.416 views 0 download

Tags:

Transcript of Linq 1224887336792847 9

Daniel N. EganMicrosoft Regional Director – California

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

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

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

degan@ocgpros.com 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

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 TYPEDAssigning 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 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

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 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

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

~John Steinbeck

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

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.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 )}

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 "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:

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 Extension methodsmethods

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 = "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.!

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

RewriteSQL2000

ParametersFlatten

Parameters

Readers

Format

DataContext

SubmitChange

Processor

Walk Objects

TX

Sequence

Do the Update

Dynamic

UserOverride