reflection it linq & entity framework fons sonnemans (trainer) [email protected]

34
R e f l e c t i o n I T LINQ & Entity Framework Fons Sonnemans (Trainer) [email protected] http://www.reflectionit.nl

Upload: dylan-lyons

Post on 26-Dec-2015

241 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

Reflectio

n IT

LINQ & Entity Framework

Fons Sonnemans (Trainer)

[email protected] http://www.reflectionit.nl

Page 2: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

2

Agenda

• C# 3.0• LINQ• LINQ to SQL• Entity Framework

Page 3: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

3

ADO.NET Problemsusing (SqlConnection c = new SqlConnection(…)) {

c.Open();

string sql = "SELECT c.Name, c.Phone, c.CreationDate " +"FROM Customers c " +

"WHERE c.City= @p0"

SqlCommand cmd = new SqlCommand(sql, c);

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

SqlDataReader dr = c.ExecuteReader(cmd);

while(dr.Read()) {string name = dr.GetString(0);string phone = dr.GetString(1);DateTime date = dr.GetDateTime(2);…

}}

Queries in quotes

Loosely bound arguments

Loosely typed resultsets

No compiletime checking

No IntelliSense

Page 4: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

Reflectio

n IT

C# 3.0

Page 5: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

5

C# 3.0: Local Variable Type Inference• Local variable type inference is a feature in

C# 3.0 where you can use the var keyword instead of explicitly specifying the type of a variable. The C# 3.0 compiler makes the type of the variable match the type of the right side of the assignment.

public void Foo() {

var i = 5;var s = "Hello";var d = 1.0;

var z; // compiler error, no initializerz = DateTime.Today;

}

Page 6: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

6

C# 3.0: Object Initializers

public class Point{ private int x, y;

public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } }}

Point a = new Point { X = 0, Y = 1 };

Point a = new Point();a.X = 0;a.Y = 1;

Field or property assignments

Page 7: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

7

C# 3.0: Anonymous Types

• Different anonymous object initializers that define properties with same names in the same order generate the same anonymous type

var emp = new { Name = "Fons", Salary = 2000, DateTime.Today.Year };

var year = emp.Year;

class XXX { public string Name { get; set; } public int Salary { get; set; } public int Year { get; set; }}

Page 8: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

8

C# 3.0: Extension Methods

• Extend existing types with additional methods.namespace MyStuff {

public static class Util {

public static bool IsWeekend(this DateTime value) { return (value.DayOfWeek == DayOfWeek.Sunday || value.DayOfWeek == DayOfWeek.Saturday);

}}

}

using MyStuff;

Brings extensions into scope

dt.IsWeekend()

DateTime.IsWeekend(dt)DateTime dt = DateTime.Today;bool b = dt.IsWeekend();

Page 9: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

9

C# 3.0: Lambda Expressionsdelegate string SomeDelegate(string s);

private static string TestMethod1(string s) { return s.ToUpper();}…SomeDelegate d1 = new SomeDelegate(TestMethod1);string a = d1("abcde");

SomeDelegate d3 = delegate(string s) { return s.ToUpper();};string a = d3("abcde");

SomeDelegate d4 = s => s.ToUpper();string a = d4("abcde");

C# 1.0

C# 2.0

C# 3.0

SomeDelegate d2 = TestMethod1;string a = d2("abcde");C# 2.0

Delegate Inference

Anonymous Method

Lambda Expression

OO Function- Pointer

Page 10: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

Reflectio

n IT

LINQ

Language-Integrated Query

Page 11: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

11

What is LINQ?

• Uniform way to write queries over data Data == Objects Imperative Declarative Works against objects, relational and XML

• LINQ is about query keywords Built into new languages C# 3.0 and VB 9.0

• LINQ is about query operators 40+ standard query operators are defined Methods that operate in queries or act on its

results

Page 12: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

12

C# 3.0: Query Expressions

from id in source{ from id in source | join id in source on expr equals expr [ into id ] | let id = expr | where condition | orderby ordering, ordering, … } select expr | group expr by key[ into id query ]

Starts with from

Zero or more from, join, let, where, or

orderby

Ends with select or group by

Optional into continuation

Page 13: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

13

from c in customerswhere c.State == "WA"select new { c.Name, c.Phone };

customers.Where(c => c.State == "WA").Select(c => new { c.Name, c.Phone });

C# 3.0: Query Expressions

• Queries translate to method invocations Where, Join, OrderBy, Select, GroupBy, …

Page 14: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

14

Language-Integrated Query

Others…VBC#

LINQ ProviderLINQ Provider

ADO.NET BasedADO.NET Based

LINQTo Datasets

LINQTo SQL

LINQTo Entities

LINQTo XML

LINQTo Objects

ObjectsObjects

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

XMXMLL

RelationRelationalal

Page 15: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

15

Two kinds of LINQ

Enumerable types

Queryable types

Execution Local in-memory Usually remote

Implementation Iterators using yield return

Expression tree parsing

Interface IEnumerable<T> IQueryable<T>

Providers LINQ to Objects LINQ to SQLLINQ to Entities

Other APIs LINQ to XMLLINQ to DataSets

Page 16: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

16

Standard Query OperatorsRestriction Where

Projection Select, SelectMany

Ordering OrderBy, OrderByDescending, ThenBy, ThenByDecending

Grouping GroupBy

Quantifiers Any, All, Contains

Partitioning Take, Skip, TakeWhile, SkipWhile

Sets Distinct, Union, Concat, Intersect, Except

Elements First, FirstOrDefault, Last, Single, ElementAt

Aggregation

Count, Sum, Min, Max, Average

Conversion ToArray, ToList, ToDictionary, ToLookup

Casting Cast<T>, OfType<T>

Page 17: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

17

LINQ to Objects

Page 18: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

18

LINQ to SQL

• O/R Mapper Maps .NET classes to relational SQL Server data

• Translates LINQ queries to SQL execution

• Supports change tracking for insert, update, delete operations

• Built on top of ADO.NET and integrates with connection-pooling and transactions

Page 19: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

19

LINQ to SQL

from c in db.Customerswhere c.City == "London"select c.CompanyName

IQueryable<IQueryable<T>T>

SELECT CompanyNameFROM CustomerWHERE City = 'London'

SQL Query or SProcSQL Query or SProc ResultsetResultset

ObjectsObjects

db.Customers.InsertOnSubmit(c1);

c2.City = "Asten";

db.Customers.DeleteOnSubmit(c3);

SubmitChanges()SubmitChanges()

INSERT INTO Customer …UPDATE Customer …DELETE FROM Customer …

DML or SProcsDML or SProcs

[Attributes]

ApplicationApplication

SQL Server

LINQ to SQL(DataContext)LINQ to SQL

(DataContext)

Page 20: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

20

LINQ to SQL

Page 21: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

Reflectio

n IT

ADO.NET Entity Framework

Included in Visual Studio SP1

Page 22: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

22

ADO.NET Entity Framework

• O/R Mapper Maps .NET classes to relational SQL data

• Translates LINQ and Entity SQL queries to SQL execution

• Supports change tracking for insert, update, delete operations

• Built on top of ADO.NET and integrates with connection-pooling and transactions

Page 23: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

23

ADO.NET Entity Framework

RDBMS

DatastoreObjectsSchema

DatastoreObjectsSchema

Entity Data Model

Schema

Entity Data Model

Schema

Conceptual Model Storage/Logical Model

*.CSDL

*.MSL*.SSD

L

Map

ObjectConnection

ObjectCommand

ObjectDataReader

ObjectConnection

ObjectCommand

ObjectDataReader

EntityClient (ADO.NET API )

SQL ServerSQL Server

Providers

OracleOracle DB2DB2

Object Services (ORM API)

ObjectContextEntityObject

ObjectContextEntityObject ObjectQueriesObjectQueries

Entity SQL DataReader LINQ Objects Entity SQL Objects

• Entity Data Model Abstraction over a relational

database Consists of conceptual & logical

models Provides mapping layer between

conceptual model and logical model

• Entity Client Provides classes similar to ADO.NET

Providers Can return results as

DbDataReaders

• Entity SQL Textual SQL language for dynamic

queries

• Object Services Enables you to work with object

instances Provides persistence and change

tracking

• LINQ to Entities Provides LINQ syntax and strongly-

typed objects for queries over EDM

Entity Data Model

Page 24: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

24

Entity Data Model• The edmx file is composed of three important

parts: • The csdl section which describes your entities• The ssdl section which describes your database• The msl section which do the mapping between the two others

RDBMS(tables, views,

SP’s, FN’s)

OO Classes

(Properties + Methods)

OO Classes

(Properties + Methods)

DatastoreObjectsSchema

DatastoreObjectsSchema

Entity Data Model

Schema

Entity Data Model

Schema

Conceptual Model

Storage/Logical Model

*.CSDL

*.MSL*.SSD

L

Map

Page 25: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

25

Mapping Examples

Store

CustomerCustomer

CustomerId

First

Last

EntitiesMapping

CustomersCustomers

ID

FirstName

LastName

IsPremium

Overdraft

AccountManagerPremiumCustomerPremiumCustomer

Overdraft

AccountManager

?

Page 26: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

26

Mapping Examples

Store

Good CustomersGood Customers

IDFirstNameLastName

Bad CustomersBad Customers

IDForeNameSurname

CustomersCustomers

CustomerIdFirstLastType

EntitiesMapping

Type=“G”

Type=“B”

Page 27: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

27

LINQ to Entity Framework

from c in db.Customerswhere c.City == "London"select c.CompanyName

IQueryable<IQueryable<T>T>

SELECT CompanyNameFROM CustomerWHERE City = 'London'

SQL Query or SProcSQL Query or SProc ResultsetResultset

ObjectsObjects

db.AddToCustomer(c1);

c2.City = "Asten";

db.DeleteObject(c3);

SaveChanges()SaveChanges()

INSERT INTO Customer …UPDATE Customer …DELETE FROM Customer …

DML or SProcsDML or SProcs

.edmx File(Models &Mapping)

ApplicationApplication

RDBMS

LINQ to EF(ObjectContext)

LINQ to EF(ObjectContext)

Page 28: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

28

Entity SQL (SELECT only)// Object Services using (NorthwindEntities db = new NorthwindEntities()) {

// Entity SQL var q = db.CreateQuery<Products>("SELECT VALUE p FROM NorthwindEntities.Products AS

p " +"WHERE p.UnitPrice > @price", new ObjectParameter("price", 60));

foreach (var prod in q) { Console.WriteLine(prod.ProductName); }

}

// Entity Clientusing (EntityConnection con = new EntityConnection("name=NorthwindEntities")) { con.Open();

// Entity SQL EntityCommand cmd = new EntityCommand("SELECT p.ProductName FROM

NorthwindEntities.Products" + " AS p WHERE p.UnitPrice > @price", con);

cmd.Parameters.AddWithValue("price", 60);

using (EntityDataReader r = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { while (r.Read()) { Console.WriteLine(r["ProductName"]); } }}

Page 29: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

29

EF Providers in Progress

Vendor DB Support

Microsoft SQL Server

Core Lab Oracle, MySQL, PostgreSQL, SQLite

IBM DB2, Informix Dynamic Server

MySQL AB MySQL

Npgsql PostgreSQL

OpenLink Many via OpenLink ODBC or JDBC

Phoenix SQLite

DataDirect Oracle, Sybase, SQL Server, DB2

Firebird Firebird

Page 30: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

30

LINQ to SQL vs Entity Framework

LINQ to SQL ADO.NET Entities Framework

Database Support

SQL Server Many

Object Relational Mapping Capabilities

Simple -> 1:1 Complex

Metadata Attributes edmx file

Status Released Beta, Summer 2008

Page 31: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

31

ADO.NET Entity Framework

Page 32: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

32

Summary

• LINQ is a really important technology

• Native query integration within languages improves productivity and error checking

• LINQ to SQL and ADO.NET Entity Framework are both O/R Mappers

• Using LINQ in ASP.NET is both easy and fun

Page 33: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

33

Resources

• http://www.datadeveloper.net/ • http://code.msdn.microsoft.com/adonetefx • http://msdn.microsoft.com/en-us/

netframework/aa904594.aspx • http://blogs.msdn.com/adonet/default.aspx

• Visual Studio 2008 Upgrade Training http://www.reflectionit.nl/Training/

default.aspx#orcas

Page 34: Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl

34

Questions

mailto:[email protected] http://www.reflectionit.nl

http://www.objectmap.nl