- LINQ to SQL provides a lighter-weight ORM focused only on SQL Server, while Entity Framework supports multiple databases.
- LINQ to SQL uses a code-first approach and only supports simple 1-to-1 mapping, while Entity Framework uses a model-first approach and supports more complex mapping scenarios.
- Entity Framework has richer modeling capabilities through the Entity Data Model (EDM), while LINQ to SQL has more limited modeling.
- Entity Framework is the recommended Microsoft ORM going forward, while LINQ to SQL is considered a predecessor and will be maintained but not actively developed.
2. This is Your Life...
You build applications for a living
Each talks to relational database
Learn (at least) 2 different languages (C# and SQL)
– Different syntax
– Different type systems
– Different tools
– Different paradigms: Object vs. Procedural
Also must learn the API that binds together: ADO.NET
– Powerful, but fragile and time-consuming
Rob Vettor 2
3. Here is What You Do…
using (SQLConnection conn = new SQLConnection(“<conn string>”);
{
conn.Open();
SQLCommand cmd = conn.CreateCommand();
cmd.CommandText = “sp_StoredProc”;
cmd.parameters.AddWithValue(“@City”, “Dallas”);
using (SQLDataReader rdr = cmd.ExecuteReader())
{
while (rdr.read())
{
string name = rdr.GetString(0); Parameters loosely bound: --
string city = rdr.GetString(1); Strings! No compile
Names, types, number of
Results are loosely typed
} not checked or Intellisense
time check until runtime
}
}
Powerful, but fragile and time-consuming
Rob Vettor 3
4. Bigger Problem
Objects != Relational Data
OO been around for decades; relational databases even
longer
Bridging the gap between has been time consuming and
expensive:
– Legacy ADO.NET Objects
Relational Data
– Hand-built DALs
– 3rd party frameworks
But, the core problem remains!
4
5. So, Now…
Instead of building business functionality,
Application Database
Customer.cs dbo.customer
Mapping Code
Transform OO to DB
Order.cs dbo.order
We build plumbing
to move data back and forth
from data store to business objects.
Rob Vettor 5
6. Goals
Fly over the Entity Framework @ 5,000 feet
What it is
What it does
How it works
Why it exists
Test drive examples
Where to find more
Rob Vettor 6
7. Autobiographical Stuff…
Architect/Team Lead
C# MVP
INETA Regional Speaker
Frequent Presenter
User Group Leader
Developer Guidance Council member
Rob Ve 7
8. Spot Survey
How many use EF in production app?
How many have looked at EF?
How many have looked at LINQ?
How many use Visual Studio 2008?
How many use Visual Studio 2008 and
not LINQ?
Rob Vettor 8
9. Appeal
Need your feedback and support:
– If you like presentation, please send email
– Consider lobbying User Group leader to have
me present any of the following:
– Getting Started with Entity Framework
– Getting Started with LINQ
– Advanced LINQ
– Entity Framework 4.0
– ADO.NET Data Services
Rob Vettor 9
10. Agenda
s Define Entity Framework
s Explore its Architecture
s Map Conceptual Model
s Program Conceptual Model
s Examine Key Concepts
s Compare EF vs. L2S
s How to get started
–
Rob Vettor 10
11. What is the Entity Framework?
Released in July 2008, EF is a data access framework
from Microsoft that helps bridge the gap between data
structures and objects in your applications.
ADO.NET Evolution
“Legacy”
ADO.NET ADO.NET Azure
RIA
2.0 Data Table
Services
Services Services
Underlying Framework for…
Rob Vettor 11
12. What Does It Do?
s Develop against conceptual view of your data,
instead of data store itself
s Automatically generates strongly-typed entity objects that
can be customized beyond 1-1 mapping
s Automatically generates mapping/plumbing code
s Automatically translates LINQ queries to database queries
s Automatically materializes objects from data store calls
s Automatically tracks changes, generating updates/inserts
s Delivers variety of visual modeling tools
Rob Vettor 12
13. From a LINQ Perspective
Query Operators C# 3.0 VB 9.0
LINQ Proviers
LINQ to LINQ to LINQ to LINQ to LINQ to
Objects Datasets SQL Entities XML
<book>
<title/>
<author/>
<year/>
<price/>
</book>
Objects XML
Relational
Rob Vettor 13
14. ADO.NET Perspective
Entity Framework
V3.0
LINQ to Entities, Entity SQL
Programming
ADO.NET Entity Provider (entity client)
Model
Conceptual Data Model
Mapping
Legacy ADO.NET 2.0 does not go away!
ADO.NET Data Provider
(SqlClient, OracleClient)
Reader Connection Store
Adapter Command
Rob Vettor 14
16. Entity Data Model
s Set of objects that describe structure of your business
data and map to your underlying data store
Contained in Three XML sections stored in *.edmx file:
Database Entity
Schema Objects
Storage Model Mapping Conceptual Model
Database UI OO Services
s Abstracts developer from a model pleasing to a DBA
(normalized, maintainable, efficient, secure), but
complicated to program against
Rob Vettor 16
17. Summary
s Entity Framework is data access framework that
bridges gap between data and objects
s Sits beneath many of Microsoft’s new offerings:
ADODS, Azure Tables, RIA Services
s Automatically creates entity objects and mappings
s Transforms LINQ Queries into SQL
s Delivers flexible object model that enables you to
map data to objects as you like
Rob Vettor 17
18. Agenda
s The Problem
s The EF and EDM
sMapping a Conceptual Model…
s Programming a Conceptual Model
s Key Concepts…
s EF vs. L2S
s Advanced Mapping
s How to get started
Rob Vettor 18
19. Map Conceptual Model
s Designer Tour…
With mapping wizard, create a new Entity Data Model
Examine entities, scalar and navigation properties in EDM
Designer,
Look at the Model Browser
Look at the Mapping Details
Look at the EDMX file
Most importantly, look at generated entity classes
s End up with object-representation of our data store
s DEMO
Rob Vettor 19
20. Mapping Recap
Many-to-Many
Relationship Represented by navigation
Scalar Property
Navigation Property
Object that describes an that is to related entity. Properties. Suppresses
Value Pointer
Association, denoted by in Enable app to navigate association entity
contained the entity
the multiplicity of endpoint to and from.
Entity
Key domain object
distinguished by
its identity
Rob Vettor 20
21. Agenda
s The Problem
s The EF and EDM
s Mapping a Conceptual Model
sProgramming a Conceptual Model…
s Key Concepts
s EF vs. L2S
s Advanced Mapping
s How to get started
Rob Vettor 21
22. Programing Conceptual Model
Two APIs available for coding against EDM
Entity Object
Client Services
s New ADO.NET data provider
Query against conceptual model with LINQ
Managed new code generates eSQL
s Implements LINQ SQL dialect SQL
Returns ‘hierarchical’ result set , not tabular Intellisense
Compile time type checking, debugging and
Closely resembles ADO.NET, requires connections,
s Query results are “materialized” into strongly-typed objects
commands, returns data readers
s Provides automatic change tracking
Delivers high performance – returns data not objects
s Manages concurrency and transactions
Favor when need plain data, not “materialized” entities
Rob Vettor 22
23. Two Simple Demos
s eSQL Demo… and LINQ-To-Entities Demo…
Query customers from our conceptual model
Return all customers in Oregon
Render in GridView
s View generated SQL in SQL Profiler
s Demonstrate “Query Syntax” vs. “Method Syntax”
s Remember: We are querying conceptual model, not
data store
Rob Vettor 23
24. Agenda
s The Problem
s The EF and EDM
s Mapping a Conceptual Model
s Programming a Conceptual Model
sKey Concepts…
s EF vs. L2S
s Advanced Mapping
s How to get started
Rob Vettor 24
25. Key Concept: Object Context
using (NorthwindEFEntities ctx = new NorthwindEFEntities())
– Workhouse of EF
– Entry point to Entity Framework
Object
– Manages connection to data store Context
– Generates SQL queries against store
– Marshals data across boundaries and Entity
Designer
materializes entity objects
– Acts as local cache for storing the
materialized objects Target Entity
– Maintains full change tracking and Uses factory to
concurrency management Instantiate entity
Rob Vettor 25
26. Associations/Navigation Properties
s When generating from database, EF infers <PK><FK>
relationships and generates navigation properties
Multiplicity
Direction
avigate conceptual model without
explicit joins
avigation properties, enable us to
‘dot’ into related objects
Rob Vettor 26
27. Navigation Properties
– From Order, use navigation property to find related OrderDetail entities
from o in Order
where o.OrderDetails.unitPrice > 20
select o;
Order
OrderrID <pk>
Order maps reference to collection of Order Details objects (EntitySet Type)
From OrderDetails, use navigation property to find Order entities
from d in OrderDetails
where d.Order.orderID == 1
OrderDetail select d;
OriderDetailID<pk>
OrderD <fk> Order Details maps reference to single Order object (EntityRef Type)
s DEMO
Rob Vettor 27
28. Projection
s Shaping or molding the data returned by LINQ query to
include only what you need.
Can project entire sequence from collection…
Can project single value…
Can project selected fields…
– Using Concrete Type
– Using Anonymous Type…
– Builds type on-the-fly
– select new { … } (no type name followed by curly braces)
– Implements Type Inference…
– var keyword tells compiler to infer strong type from right-side expression
sDEMO
28
29. Parameterized Queries vs. Sprocs
s LINQ fully supports both approaches
s Parameterized queries
s Good for CRUD operations
s Executions plans are cached and reused
s Automatically generated by LINQ framework
s Do require server permissions at the table level
s Stored Procedures
s More complex business logic (beyond CRUD)
s Security, performance, auditing
Rob Vettor 29
30. Deferred Loading
s LINQ is built on concept of “deferred execution”
Most query operators don’t execute when declared
– //-- First, define query
– var query = from c in ctx.Customers
s where c.Region == "OR"
s orderby c.CompanyName
Define query
s
and store select c; Execute query when
in variable
s //-- Then, execute query absolutely necessary
s gvQuery.DataSource = query;
s gvQuery.DataBind();
Query gets executed when enumerated
– Bound to a DataBound control
– Execute within ForEach loop Iteration
– Transformed to collection ToList(), ToArray(), etc
Rob Vettor 30
31. Eager Loading
s Force LINQ to immediately execute query
Operators that return a singleton:
– Aggregate Methods
– Element Methods
– Retrieve specific element from sequence
– First(), Last(), ElementAt()
Collection-Conversion Operators
– ToArray(), ToList(), ToDictionary(), ToLookup()
s Include() method supports eager execution:
Retrieves parent and child entities immediately, not when
referenced
s (No Demo Yet)
Rob Vettor 31
32. Loading Single Objects
s Basic Example
– Run SQL Profiler and step thru code
– Demonstrate Deferred and Eager loading
– Explore when execution takes place
– See how each enumeration of same query
generates a separate call to DB
s DEMO NOW!
Rob Vettor 32
33. Loading Object Graphs
s Object Graph: Set of individual, but related objects, that
together form a logical whole unit
Customer Order Order Detail Product Category
s By default, with deferred execution, child objects load one
at a time (separate data store call for each) as needed.
s We can use Include() method to predefine the object graph,
forcing all entire graph to load at once with single query
s DEMO
Load object graph including Orders, Order Details
and Products
Rob Vettor 33
34. Deferred vs. Immediate
Deferred Execution
– Benefits:
– Fetches data only when needed, not all at once
– Minimize network traffic, memory consumption and
load on database
– Great for when can but fetch objects as user
requests them
– Drawbacks:
– Chatty Interface: Each request for child record
invokes explicit database query
Rob Vettor 34
35. Deferred vs. Immediate
Immediate Execution
– Benefits:
– Singe query returns all data
– Great if you know that you will need all data returned
– Drawbacks:
– Large amount of data returned, whether used or not.
Rob Vettor 35
36. Updates/Change Tracking
s ObjectContext automatically tracks changes to entities via
the ObjectStateManager object
Upon retrieval, caches original values
Tracks any changes made to entities
Dynamically constructs update/insert SQL statements
– If not updating an entity, disable Change Tracking
– ctx.Products.MergeOption = MergeOption.NoTracking;
s Next DEMO
Demonstrate change tracking
Update postal code and freight charge for an order
Watch ObjectStateManager track both changes and original values
See it generate parameterized SQL update statement
Explicitly wrap in transaction
Rob Vettor 36
37. Inserts
s Inserting with EF is multi-step process
s Create new (disconnected) entity object and populate
s Attach new entity to the ObjectContext
s Call SaveChanges() to commit to database
s Next DEMO
s Show how ObjectContext leverages inferred
relationship
s Inserts both parent and child records in correct order
s Maintains foreign key relationship
s Automatically manages the identity values
s Show that ObjectContext automatically returns new identity key
and assigns to new entity objects
Rob Vettor 37
38. Agenda
s The Problem
s The EF and EDM
s Mapping a Conceptual Model
s Programming a Conceptual Model
s Key Concepts
sEF vs. L2S…
s Advanced Mapping
s How to get started
Rob Vettor 38
39. History
s On the surface, appear to look and behave closely
LTS
– Evolved from LINQ Project, a language-development team
EF
– Evolved from Data Programmability Team (DPT) which
initially focused on the Entity SQL language
– Later adapted LINQ to work with entity objects
s LTS later moved to the Data Team
s 11/08, Data Team announced invest in EF, while
maintaining and tweaking L2S
s Microsoft will provide migration path to EF
and recommend EF over LTS
39
40. How They Differ
s General consensus:
LTS
– Strongly typed LINQ access for RAD against SQL Server only
– Support s only direct Table-Per-Type (1-to-1) mapping
– Limited out-of-the box support for complex scenarios
EF
– Designed for larger enterprise applications
– Enables complex mapping complex scenarios
– Tools and designer more robust
– Supports inheritance and many-to-many relationships
– Supports provider independence
40
41. EF vs. LTS
Category LINQ to SQL Entity Framework
Model domain model conceptual data model
Databases Supported SQL server only Many
Complexity/Learning Curve simple to use complex to use
slower development but more
Development Time rapid development
capabilities
Mapping Direct 1-to-1 Custom mapping
Inheritance hard to apply simple to apply
Support ? $$$, resources, innovation
Rob Vettor 41
42. Agenda
s The Problem
s The EF and EDM
s Mapping a Conceptual Model
s Programming a Conceptual Model
s Some Intermediate Topics
s EF vs. L2S
sAdvanced Mapping…
s How to get started
Rob Vettor 42
43. Advanced EDM Mapping
s EDM provides flexibility customizing conceptual model
s Most customizations occur in the conceptual model and
depend on the mapping layer to map to underlying store
s Designer supports following customization:
Table Per Hierarchy Inheritance mapping
Table Per Type Inheritance mapping
Entity (vertical) splitting
Rob Vettor 43
44. Mapping Between Layers
Logical Schema Table Per Type Inheritance Conceptual Schema
Contact
SalesPeople
Employee
SalesPerson
SalesOrder
SalesOrder StoreOrder
Table Per Hierarchy Inheritance
Storage Schema Mapping Con. Schema
.ssdl File .msl File .csdl File
Rob Vettor 44
45. Table-Per-Hierarchy Mapping (TPH)
s Simple inheritance that maps multiple entities to single
database table
s Mapping conditionally based on discriminator column to
differentiate records as different types
s Quick to implement, but lacks scalability – derived from single
database table Base Type
Entities
Discriminator
Column
Database Table
Employee Employee
managementFlag ManagementEmployee
s No Demo Yet
Derived Type
Rob Vettor 45
46. Using TPH
s Discriminator column identifies whether row belongs to
base or derived type
s Can include additional columns for derived type whose
value is NULL for base type (denormalized!)
s Can query on derived types without a where clause by
using OfType() method
from c in ctx.Customers.OfType<ManagementEmployees>()
s Show in Designer
s Demo
s Limitations
Difficult to update discriminator column value via EF – must
use database construct (trigger/stored proc)
Rob Vettor 46
47. Table-Per-Type Mapping
s Inheritance spanning related database tables.
s Exposes attributes from both parent table and child table into
single derived entity
s Defined in database with separate tables where one table
(child) describes new type based on another table (parent)
Database Table Entities
Customers
Tax Audit
State Tax Audit CustomersUSA
s No Demo Yet
Rob Vettor 47
48. Using TPT
s Eliminates need to programmatically traverse navigation
properties to move from child (CustUSA) to parent (Cust)
to include parent information
s When projecting on derived type, use OfType() method
from c in ctx.Customers.OfType<CustomersUSA>()
s Show in Designer, Demo
s Limitations:
Derived type is completely bound to parent type – cannot
directly access derived type; only thru parent
Cannot delete child without deleting parent
Cannot change existing customer to CustomerUSA
Rob Vettor 48
49. Entity (Vertical) Splitting
s Map single entity to multiple tables
s Tables must share common key
s Typically for 1-to-1 relationships where one table
provide additional information about another
Database Tables
Employee
Entities
EmployeeFinancial Employee
EmployeePersonal
s No Demo Yet
Rob Vettor 49
50. Using Entity (Vertical) Splitting
s Vertical Entity Partitioning
s Addresses data modeling practice of decomposing large
table into number of smaller tables
s Relives you from having to traverse navigation properties
among the tables to retrieve data
s In mapping details window, we map single entity to three
underlying tables
s Conceptual model contains single product entity
s Store (SSDL) contains three product tables
s MSL metadata maps single entity to multiple tables
Show Mapping Details in Designer; Demo
Rob Vettor 50
51. Advanced EDM Mapping
s EDM enables you to decouple and customize your
conceptual layer and design it to align more with your
business processes, rather than the highly-normalized
design a DBA might create
s The Mapping Detail Tool enables you to map your
customizations to your underlying data store layer
s Designer supports most, but not all, customization
Table Per Hierarchy Inheritance mapping
Table Per Type Inheritance mapping
Entity (vertical) splitting
Rob Vettor 51
52. Agenda
s The Problem
s The EF and EDM
s Mapping a Conceptual Model
s Programming a Conceptual Model
s Key Concepts
s EF vs. L2S
s Advanced Mapping
sGetting Started…
Rob Vettor 52
55. Questions?
Comments?
Suggestions?
robvettor@hotmail.com
http://weblogs.asp.net/dotnetarchitect
Rob Vettor 55
Notas del editor
Today, with ADO.NET 2.0, We have providers that provide connections, commands, etc that are specific to a particular data store In Version 3.0, developer can build conceptual model of the store Program against model that ties closely to domain Mapping technology translates conceptual model to real store You are abstracted from underlying store and program against conceptual model instead of logical model LINQ to Entities is object-relational mapping API mapping between conceptual model and .NET types in memory, which give you the ability to use language integrated queries to manipulate the conceptual model So. in nutshell, on top you have LINQ, with Object Relational Mapping API on top of a conceptual model, which itself is mapped to is mapped to the underlying store.