C 3 0 linq
This presentation is the property of its rightful owner.
Sponsored Links
1 / 46

C# 3.0 & LINQ PowerPoint PPT Presentation


  • 91 Views
  • Uploaded on
  • Presentation posted in: General

C# 3.0 & LINQ. 2007.11.24. Microsoft Visual C# MVP 한용희 http://blog.naver.com/woom333. Agenda. C# 3.0 New Features Local Variable Type Inference Object / Collection Initializers Anonymous Types Extension Methods Lambda Expressions Query Expressions LINQ LINQ to SQL LINQ to XML

Download Presentation

C# 3.0 & LINQ

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


C 3 0 linq

C# 3.0 & LINQ

2007.11.24

Microsoft Visual C# MVP

한용희

http://blog.naver.com/woom333


Agenda

Agenda

  • C# 3.0 New Features

    • Local Variable Type Inference

    • Object / Collection Initializers

    • Anonymous Types

    • Extension Methods

    • Lambda Expressions

    • Query Expressions

  • LINQ

    • LINQ to SQL

    • LINQ to XML

    • LINQ to Entities

    • LINQ to DataSet


C 3 0

Part 1

C# 3.0


C 1 0 2 0 3 0

C# 1.0 , 2.0, 3.0

Expression Trees

Partial Classes

delegates

Object Initializers

Accessors

Anonymous Methods

Reflection

Anonymous Classes

Nullable Types

Object Oriented

Lambda Expressions

Managed

Iterators

Extension Methods

Type Safety

Generics

Local Var’s Type Inference

Enums

LINQ


Why c 3 0

Why C# 3.0


New features

New Features

  • Local Variable Type Inference

  • Object / Collection Initializers

  • Anonymous Types

  • Extension Methods

  • Lambda Expressions

  • Query Expressions


Local variable type inference

Local Variable Type Inference

inti = 5;

string s = "Hello";

double d = 1.0;

int[] numbers = new int[] {1, 2, 3};

Dictionary<int,Order> orders = new Dictionary<int,Order>();

var i = 5;

var s = "Hello";

var d = 1.0;

var numbers = new int[] {1, 2, 3};

var orders = new Dictionary<int,Order>();

“var” means same type as initializer


C 3 0 linq

Local Variable Type Inference


Object collection initializers

Object / Collection Initializers

public class Point

{

public int x, y;

}

Field or property assignments

Point a = new Point { x = 0, y = 1};

Point a = new Point();

a.x = 0;

a.y = 1;


Object collection initializers1

Object / Collection initializers

Must implement ICollection<T>

List<int> powers = new List<int> { 1, 10, 100, 1000, 10000 };

List<int> powers = new List<int>();

powers.Add(1);

powers.Add(10);

powers.Add(100);

powers.Add(1000);

powers.Add(10000);


C 3 0 linq

Object / Collection initializers


Anonymous types

Anonymous Types

  • Fits with complex temporarily variables

var x = new { a = 3, b = 5, c = “some text” };

class __Anonymous1

{

private int _a = 3;

private int _b = 5;

private string _c = “some text”;

public int a { get { return v1; } set { _a = value; } }

public int b { get { return v2; } set { _b = value; } }

public int c { get { return v3; } set { _c = value; } }

}


C 3 0 linq

Anonymous Types


Extension methods

Extension Methods

public static class Extensions

{

public static int ToInt32(this string s)

{

return Int32.Parse(s);

}

}

string s="1234";

int i = s.ToInt32(); // Same as Extensions.ToInt32(s)

  • The ability to extend existing types.

    • Add new functions to existing classes.

    • No need for editing the existing codes.

  • Simpler than inheritance.

    • Inheritance will not work with sealed or primitive types.

    • Inheritance is limited by class accessibility.


C 3 0 linq

Extension Methods


Lamda expressions

Lamda Expressions

  • Old Programming Concept (λ-calculus).

  • Exists in most dynamic languages .

    • Python, Lisp, Ruby

  • Evolution of anonymous functions.

<Delegate Type> identifier = (<param list>) => <Expression>

Func<int, int> increment = i => i+1;

Increment(10);// result is 11


Lamda expressions1

Lamda Expressions

delegate stringSomeDelegate(string s);

static string TestMethod1(string s)

{

return s.ToUpper();

}

SomeDelegate d1 = new SomeDelegate(TestMethod1);

string a = d1(“abcde");

C# 1.0

C# 2.0

C# 3.0

SomeDelegate d2 = delegate(string s)

{

return s.ToUpper();

};

string a = d2("abcde");

Implicitly typed

SomeDelegate d3 = s => s.ToUpper();

string a = d3("abcde");


C 3 0 linq

Lamda Expressions


Query expressions

Query Expressions

Query expressions

var contacts =

from c in customers

where c.City == “London"

select new { c.CustomerID, c.City };

Implicitly typed Local variable

Lambda expressions

var contacts =

customers

.Where(c => c.City == “London")

.Select(c => new { c.CustomerID, c.City });

Extension methods

Anonymous types

Object initializers


C 3 0 linq

Query Expressions


Language integrated query linq

Part 2

Language INtegrated Query(LINQ)


Problems

Problems

Projection, Join, Grouping, Queries

(Declarative)

OOP, Inheritance, Polymorphism, Loops, Conditions …etc

(Imperative)


Linq project goals

LINQ Project Goals

  • Unified programming model for any data type

    • Database Relational Data

    • XML Files

    • Collections & Arrays

  • Introduce more declarative syntax

    • Helps the system find the best execution strategy

      • Parallel LINQ (PLINQ)


The linq project

<book>

<title/>

<author/>

<year/>

<price/>

</book>

Relational

Objects

XML

The LINQ Project

.NET Language Integrated Query

C# 3.0

VB 9.0

Others

LINQ toDataSets

LINQ toEntities

LINQ toSQL

LINQ toXML

LINQ toObjects


Linq to sql

LINQ to SQL

Accessing data today

Queries in quotes

SqlConnection c = new SqlConnection(…);

c.Open();

SqlCommand cmd = new SqlCommand(

@"SELECT c.Name, c.Phone

FROM Customers c

WHERE c.City = @p0");

cmd.Parameters.AddWithValue("@p0", "London“);

DataReader dr = c.Execute(cmd);

while (dr.Read()) {

string name = dr.GetString(0);

string phone = dr.GetString(1);

DateTime date = dr.GetDateTime(2);

}

dr.Close();

Loosely bound arguments

Loosely typed result sets

No compile time checks


Linq to sql1

LINQ to SQL

Accessing data with LINQ to SQL

Classes describe data

public class Customer { … }

public class Northwind: DataContext

{

public Table<Customer> Customers;

}

Tables are like collections

Strongly typed connection

Northwind db = new Northwind(…);

var contacts =

from c in db.Customers

where c.City == "London"

select new { c.Name, c.Phone };

Integrated query syntax

Strongly typed results


Linq to sql architecture

LINQ to SQL Architecture

db.Customers.Add(c1);

c2.City = “Seattle";

db.Customers.Remove(c3);

from c in db.Customers

where c.City == "London"

select c.CompanyName

Enumerate

Objects

SubmitChanges()

SQL Queryor SProc

Rows

DML or SProcs

SQL Server

INSERT INTO Customer …

UPDATE Customer …DELETE FROM Customer …

SELECT CompanyName

FROM Customer

WHERE City = 'London'

Application

LINQ to SQL


Standard query operators

Standard Query Operators


C 3 0 linq

LINQ to SQL


Linq to xml

LINQ to XML

Programming XML today

Imperative model

XmlDocument doc = new XmlDocument();

XmlElement contacts = doc.CreateElement("contacts");

foreach (Customer c in customers)

if (c.Country == "USA") {

XmlElement e = doc.CreateElement("contact");

XmlElement name = doc.CreateElement("name");

name.InnerText = c.CompanyName;

e.AppendChild(name);

XmlElement phone = doc.CreateElement("phone");

phone.InnerText = c.Phone;

e.AppendChild(phone);

contacts.AppendChild(e);

}

doc.AppendChild(contacts);

Document centric

No integrated queries

Memory intensive

<contacts>

<contact>

<name>Great Lakes Food</name>

<phone>(503) 555-7123</phone>

</contact>

</contacts>


Linq to xml1

LINQ to XML

Programming XML with XLinq

Declarative model

XElement contacts = new XElement("contacts",

from c in customers

where c.Country == "USA"

select new XElement("contact",

new XElement("name", c.CompanyName),

new XElement("phone", c.Phone)

)

);

Elementcentric

Integrated queries

Smaller and faster


C 3 0 linq

LINQ to XML


Guidance for linq to relational data

Guidance for LINQ to Relational Data

  • LINQ to SQL – Strongly Typed Database

    • Emphasis on rapid application development

    • Direct mapping to Microsoft SQL Server family of databases

    • Release in Microsoft Visual Studio 2008 RTM

  • LINQ to Entities – Flexible mapping to existing Schema

    • Focus on enterprise-grade data scenarios

    • Flexible Mapping to Microsoft SQL Server and third-party databases

    • Release in Microsoft Visual Studio 2008 update

      • CTPs on top of Microsoft Visual Studio 2008 Betas/RTM

  • LINQ to DataSet – In-Memory Cache w/Change Tracking

    • All the scenarios where DataSet is useful today

      • Offline, Disconnected, Aggregation

      • Change Tracking

        ..Plus support for Query Operations

    • Strongly typed or Untyped DataSet Support

    • Release in Microsoft Visual Studio 2008 RTM


Linq to sql strongly typed sql database

LINQ to SQLStrongly typed SQL Database

  • Design Points

    • Rapid Development against SQL Database

      • Direct Mapping to SQL Server Schema

      • Mappings expressed in Attributes or XML file

    • "Just Work" for common scenarios

      • Execute when needed

      • Naming Conventions

        • Business Logic

        • Custom Insert/Update/Delete operations

    • Minimally Intrusive object model

    • Provide Customization, Optimizations where required

  • Targets: Microsoft SQL Server

  • RTM: Microsoft Visual Studio 2008 RTM


Linq to sql direct mapping

LINQ to SQLDirect Mapping

  • Direct Mapping

    • Each class maps to a single SQL Schema Object

      • Table, View

      • Stored Procedure, Table Valued Function

    • Simple renaming of Tables, Columns

    • Foreign Keys can be expressed as Relationships

      • Properties to navigate in query, results

    • Inheritance

      • Multiple Classes in a Hierarchy can map to a single Table/View/Stored Proc/TVF with a discriminator column


Linq to sql features

LINQ to SQLFeatures

  • Customization

    • Business Logic

      • Partial classes for generated Objects

        • Add Methods, non-persistent members, etc.

        • Business Logic through Partial methods based on naming conventions

    • Update Logic

      • Implement partial methods in derived Class

        • Call Stored Procedures or invoke custom logic

  • Optimizations

    • Loading Options

      • ObjectTrackingEnabled

      • DeferredLoadingEnabled

    • Compiled Query

      • Save overhead of SQL generation from Language Expression


C 3 0 linq

Direct Mapping with LINQ to SQL


Linq to entities flexible mapping to relational data

LINQ to EntitiesFlexible Mapping to Relational Data

  • Design Points

    • Flexible Mapping to Existing Relational Schema

      • Well defined Conceptual model

        • Share common model across products (Reporting, Analysis, etc…)

      • Declarative Mapping between Application and Store

        • Allows Storage Schema and Application to evolve independently

    • Explicit Operations

      • Server interactions should be explicit

        • Build implicit logic on top of explicit operations

    • Common Textual "EntitySQL" Language for Ad-Hoc queries

  • Targets: Microsoft SQL Server and third-party databases

  • RTM: Microsoft Visual Studio 2008 Update H1CY08


Linq to entities flexible mapping to relational data1

LINQ to EntitiesFlexible Mapping to Relational Data

  • Flexible Mapping

    • Mapping a single class to multiple tables/views

    • Mapping to different types of inheritance

      • Single Table per Class Hierarchy

      • Separate Table for each Class in a Hierarchy

      • Shared Table for Base Class members in a Hierarchy

    • Complex (composite) types

      • i.e., Street, City, Region, and Zip as "Address"

    • Directly mapping Many:Many relationships

    • Mapping to an arbitrary Query

      • Store Query

        • Expose arbitrary store query as a storage Table

      • Entity Query

        • Express mapping as EntitySQL against storage schema


Linq to entities features

LINQ to EntitiesFeatures

  • Customization

    • Business Logic

      • Partial Classes, Events, Partial Methods

    • Update Logic

      • Generated Update Views

      • Declarative stored procedures

  • Optimizations

    • NoTracking

  • Extensibility

    • Partitioning of Metadata

    • Flexible Runtime Mapping

    • Metadata Pluggability


C 3 0 linq

Flexible Mapping with LINQ to Entities


Linq to dataset linq over disconnected cache with change tracking

LINQ to DataSetLINQ over Disconnected Cache with Change Tracking

  • Disconnected Cache

    • Offline/Remote

    • Data Aggregation

    • Application Data

      All with Change Tracking

  • Queryable

    • Filter, Projection

    • Joins

      • Across Tables

      • Other in-Memory sources

    • Local expressions

      All through Common LINQ syntax

  • RTM: Microsoft Visual Studio 2008 RTM


Linq to dataset typed and untyped

LINQ to DataSetTyped and UnTyped

  • Untyped DataSet

    • Call AsEnumerable() on DataTable

    • Reference Fields by Name

      • Use Field<T>(columnName)

    • Project out fields for strongly typed result

  • Typed DataSet

    • Use strongly typed accessors

var query = from row in myDataSet.Tables["Customers"].AsEnumerable()

where row .Field<string>("City") == "London"

select new { row.Field <string> ("CustomerID"),

row.Field <string> ("ContactName") } ;

var query = from customer in northwind.Customers

where customer.City == "London"

select customer;


C 3 0 linq

Querying Disconnected Data with LINQ to DataSet


  • Login