Reflection IT
LINQ & Entity Framework
Fons Sonnemans (Trainer)
[email protected]
http://www.reflectionit.nl
Agenda
• C# 3.0
• LINQ
• LINQ to SQL
• Entity Framework
2
ADO.NET Problems
using (SqlConnection c = new SqlConnection(…)) { Queries in
c.Open(); quotes
string sql =
"SELECT c.Name, c.Phone, c.CreationDate " +
"FROM Customers c " +
"WHERE c.City= @p0"
Loosely bound
SqlCommand cmd = new SqlCommand(sql, c); arguments
cmd.Parameters.AddWithValue("@p0", "London");
SqlDataReader dr = c.ExecuteReader(cmd); Loosely typed
resultsets
while(dr.Read()) {
string name = dr.GetString(0); No compiletime
string phone = dr.GetString(1); checking
DateTime date = dr.GetDateTime(2);
…
No
} IntelliSense
}
3
Reflection IT
C# 3.0
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 initializer
z = DateTime.Today;
}
5
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; } } Field or property
assignments
}
Point a = new Point { X = 0, Y = 1 };
Point a = new Point();
a.X = 0;
a.Y = 1;
6
C# 3.0: Anonymous Types
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; }
}
• Different anonymous object initializers that
define properties with same names in the same
order generate the same anonymous type
7
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);
}
}
}
Brings extensions
into scope
using MyStuff;
dt.IsWeekend()
DateTime dt = DateTime.Today; DateTime.IsWeekend(dt)
bool b = dt.IsWeekend();
8
C# 3.0: Lambda Expressions
delegate string SomeDelegate(string s);
private static string TestMethod1(string s) {
return s.ToUpper(); OO Function-
} Pointer
C# 1.0 …
SomeDelegate d1 = new SomeDelegate(TestMethod1);
string a = d1("abcde");
SomeDelegate d2 = TestMethod1; Delegate
C# 2.0 string a = d2("abcde"); Inference
SomeDelegate d3 = delegate(string s) {
return s.ToUpper(); Anonymous
C# 2.0 }; Method
string a = d3("abcde");
SomeDelegate d4 = s => s.ToUpper(); Lambda
C# 3.0 string a = d4("abcde"); Expression
9
Reflection IT
LINQ
Language-Integrated Query
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
11
C# 3.0: Query Expressions
Starts with
from
Zero or more from,
join, let, where, or
from id in source orderby
{ from id in source |
join id in source on expr equals expr [ into id ] |
let id = expr |
where condition | Ends with select
or group by
orderby ordering, ordering, … }
select expr | group expr by key
[ into id query ]
Optional into
continuation
12
C# 3.0: Query Expressions
• Queries translate to method invocations
Where, Join, OrderBy, Select, GroupBy, …
from c in customers
where c.State == "WA"
select new { c.Name, c.Phone };
customers
.Where(c => c.State == "WA")
.Select(c => new { c.Name, c.Phone });
13
Language-Integrated Query
C# VB Others…
LINQ Provider
ADO.NET Based
LINQ LINQ LINQ
LINQ LINQ
To Objects To Datasets To XML
To SQL To Entities
<book>
<title/>
<author/>
<price/>
</book>
Objects Relational XM
L
14
Two kinds of LINQ
Enumerable types Queryable types
Execution Local in-memory Usually remote
Implementation Iterators using yield Expression tree parsing
return
Interface IEnumerable<T> IQueryable<T>
Providers LINQ to Objects LINQ to SQL
LINQ to Entities
Other APIs LINQ to XML
LINQ to DataSets
15
Standard Query Operators
Restriction 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>
16
LINQ to Objects
17
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
18
LINQ to SQL
db.Customers.InsertOnSubmit(c1);
from c in db.Customers
where c.City == "London" Application c2.City = "Asten";
select c.CompanyName
db.Customers.DeleteOnSubmit(c3);
IQueryable<T> Objects SubmitChanges()
[Attributes] LINQ to SQL
(DataContext)
SQL Query or SProc Resultset DML or SProcs
SELECT CompanyName INSERT INTO Customer …
FROM Customer UPDATE Customer …
WHERE City = 'London' SQL Server DELETE FROM Customer …
19
LINQ to SQL
20
Reflection IT
ADO.NET Entity Framework
Included in Visual Studio SP1
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
22
ADO.NET Entity Framework
Entity SQL DataReader LINQ Objects Entity SQL Objects
• Entity Data Model
Abstraction over a relational database
EntityClient (ADO.NET API ) Object Services (ORM API)
Consists of conceptual & logical models
Provides mapping layer between ObjectConnection
ObjectContext
ObjectCommand ObjectQueries
ObjectQueries
conceptual model and logical model ObjectDataReader EntityObject
• Entity Client
Provides classes similar to ADO.NET
Providers Entity Data Model
Conceptual Model Map Storage/Logical Model
Can return results as DbDataReaders
Datastore
Datastore
• Entity SQL Entity Data Model
Schema
Objects
Objects
Schema
Schema
Textual SQL language for dynamic *.CSDL *.MSL *.SSDL
queries
• Object Services Providers
Enables you to work with object
instances SQL Server Oracle DB2
Provides persistence and change
tracking
• LINQ to Entities
Provides LINQ syntax and strongly-
typed objects for queries over EDM
RDBMS
23
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
Conceptual Model Map Storage/Logical Model
Entity Data Datastore
Model Objects
Schema Schema
*.CSDL *.MSL *.SSDL
OO Classes RDBMS
(Properties + (tables, views,
Methods) SP’s, FN’s)
24
Mapping Examples
Store Mapping Entities
Customers Customer
ID CustomerId
FirstName First
LastName Last
IsPremium
?
Overdraft
AccountManager
PremiumCustomer
Overdraft
AccountManager
25
Mapping Examples
Store Mapping Entities
Good Customers Type=“G”
ID Customers
FirstName CustomerId
LastName First
Last
Bad Customers Type
ID
ForeName
Type=“B”
Surname
26
LINQ to Entity Framework
db.AddToCustomer(c1);
from c in db.Customers
where c.City == "London" Application c2.City = "Asten";
select c.CompanyName
db.DeleteObject(c3);
IQueryable<T> Objects SaveChanges()
.edmx File
(Models & LINQ to EF
Mapping) (ObjectContext)
SQL Query or SProc Resultset DML or SProcs
SELECT CompanyName INSERT INTO Customer …
FROM Customer UPDATE Customer …
WHERE City = 'London' RDBMS DELETE FROM Customer …
27
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 Client
using (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"]);
}
}
}
28
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
29
LINQ to SQL vs Entity Framework
LINQ to SQL ADO.NET Entities
Framework
Database Support SQL Server Many
Object Relational Simple -> 1:1 Complex
Mapping
Capabilities
Metadata Attributes edmx file
Status Released Beta, Summer 2008
30
ADO.NET Entity Framework
31
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
32
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
33
Questions
mailto:[email protected]
http://www.reflectionit.nl
http://www.objectmap.nl
34