Getting started with entity framework revised 9 09
-
Upload
manisoft84 -
Category
Technology
-
view
972 -
download
7
description
Transcript of Getting started with entity framework revised 9 09
This is Your Life...
Rob Vettor 2
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
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); string city = rdr.GetString(1);}
}}
Powerful, but fragile and time-consuming
Rob Vettor 3
Here is What You Do…
Strings! No compile time check or Intellisense
Parameters loosely bound: --Names, types, number ofnot checked until runtimeResults are loosely typed
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
– Hand-built DALs
– 3rd party frameworks
But, the core problem remains!
Bigger Problem
4
Relational Data Objects
So, Now…
Rob Vettor 5
Application
Customer.cs
Order.cs
Database
dbo.customer
dbo.order
Mapping CodeTransform OO to DB
We build plumbing to move data back and forth
from data store to business objects.
Instead of building business functionality,
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
Goals
Rob Vettor 6
Architect/Team Lead C# MVP INETA Regional Speaker Frequent Presenter User Group Leader Developer Guidance Council member
Autobiographical Stuff…
7Rob Ve
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?
Spot Survey
Rob Vettor 8
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
Appeal
Rob Vettor 9
Define Entity Framework Explore its Architecture Map Conceptual Model Program Conceptual Model Examine Key Concepts Compare EF vs. L2S How to get started
–
Rob Vettor 10
Agenda
What is the Entity Framework?
Rob Vettor 11
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 EvolutionADO.NET Evolution
“Legacy”ADO.NET
2.0
ADO.NETData
Services
AzureTable
Services
Underlying Framework for…
RIAServices
What Does It Do?
Rob Vettor 12
Develop against conceptual view of your data, instead of data store itself Automatically generates strongly-typed entity objects that
can be customized beyond 1-1 mapping
Automatically generates mapping/plumbing code
Automatically translates LINQ queries to database queries
Automatically materializes objects from data store calls
Automatically tracks changes, generating updates/inserts
Delivers variety of visual modeling tools
generate strongly-typed classes, giving intellisense, compile-time and debugger supportabstract data to be more business friendly and less normalized
visual modeling tools
Develop against a conceptual view of your underlying data, not the store itself
Plumbing and mapping is done for you Not tied to SQL Server Most critically…
Generates and maintains entity classes Generates code for interacting with database, including connection Translates LINQ queries to database queries Automatically tracks changes
From a LINQ Perspective
Rob Vettor 13
ObjectsObjects
<book><book> <title/><title/>
<author/><author/> <year/><year/> <price/><price/></book></book>
XMLXML
LINQ ProviersLINQ Proviers
C# 3.0C# 3.0 VB 9.0VB 9.0
RelationalRelational
LINQ toLINQ toObjectsObjects
LINQ toLINQ toSQLSQL
LINQ toLINQ toXMLXML
LINQ toLINQ toEntitiesEntities
LINQ toLINQ toDatasetsDatasets
Query Operators
ADO.NET Perspective
Rob Vettor 14
Store
ADO.NET Data Provider(SqlClient, OracleClient)
Command
ConnectionReader
Adapter
V3.0
Conceptual Data Model
Legacy ADO.NET 2.0 does not go away!
ADO.NET Entity Provider (entity client)
LINQ to Entities, Entity SQL
Entity Framework
Programming Model
Map
pin
g
Architectural Layering
Rob Vettor
15
EntityClient
Object Services
EDMCoreof EF
Entity Data Model
Set of objects that describe structure of your business data and map to your underlying data store
Abstracts developer from a model pleasing to a DBA (normalized, maintainable, efficient, secure), but complicated to program against
Rob Vettor 16
Contained in Three XML sections stored in *.edmx file:
DatabaseSchema
EntityObjects
MappingStorage Model Conceptual Model
Database ServicesOOUI
Summary
Entity Framework is data access framework that bridges gap between data and objects
Sits beneath many of Microsoft’s new offerings: ADODS, Azure Tables, RIA Services
Automatically creates entity objects and mappings
Transforms LINQ Queries into SQL
Delivers flexible object model that enables you to map data to objects as you like
Rob Vettor 17
The Problem
The EF and EDM
Mapping a Conceptual Model… Programming a Conceptual Model
Key Concepts…
EF vs. L2S
Advanced Mapping
How to get started
Rob Vettor 18
Agenda
Map Conceptual Model
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
End up with object-representation of our data store
DEMO
Rob Vettor 19
Mapping Recap
Rob Vettor 20
EntityKey domain object distinguished by
its identity
Scalar PropertyValue that is
contained in the entity
Navigation PropertyPointer to related entity.Enable app to navigate
to and from.
RelationshipObject that describes an Association, denoted by
the multiplicity of endpoint
Many-to-ManyRepresented by navigation
Properties. Suppresses association entity
The Problem
The EF and EDM
Mapping a Conceptual Model
Programming a Conceptual Model… Key Concepts
EF vs. L2S
Advanced Mapping
How to get started
Rob Vettor 21
Agenda
Programing Conceptual Model
Rob Vettor 22
Two APIs available for coding against EDM
EntityClient
Object Services
New ADO.NET data provider
Implements new SQL dialect eSQL
Returns ‘hierarchical’ result set , not tabular
Closely resembles ADO.NET, requires connections, commands, returns data readers
Delivers high performance – returns data not objects
Favor when need plain data, not “materialized” entities
Query against conceptual model with LINQ
Managed LINQ code generates SQL
Compile time type checking, debugging and Intellisense
Query results are “materialized” into strongly-typed objects
Provides automatic change tracking
Manages concurrency and transactions
Two Simple Demos eSQL Demo… and LINQ-To-Entities Demo…
Query customers from our conceptual model
Return all customers in Oregon
Render in GridView
View generated SQL in SQL Profiler
Demonstrate “Query Syntax” vs. “Method Syntax”
Remember: We are querying conceptual model, not data store
Rob Vettor 23
The Problem
The EF and EDM
Mapping a Conceptual Model
Programming a Conceptual Model
Key Concepts… EF vs. L2S
Advanced Mapping
How to get started
Rob Vettor 24
Agenda
Key Concept: Object Context
– Workhouse of EF– Entry point to Entity Framework– Manages connection to data store– Generates SQL queries against store– Marshals data across boundaries and
materializes entity objects – Acts as local cache for storing the
materialized objects– Maintains full change tracking and
concurrency management
Rob Vettor 25
EntityDesigner
Object Context
Target Entity
using (NorthwindEFEntities ctx = new NorthwindEFEntities())
Uses factory to Instantiate entity
Associations/Navigation Properties
When generating from database, EF infers <PK><FK> relationships and generates navigation properties Multiplicity Direction
Rob Vettor 26
Navigate conceptual model without explicit joins
Navigation properties, enable us to ‘dot’ into related objects
Navigation Properties
Rob Vettor 27
– From Order, use navigation property to find related OrderDetail entities
from o in Orderwhere o.OrderDetails.unitPrice > 20select o;
From OrderDetails, use navigation property to find Order entities
from d in OrderDetailswhere d.Order.orderID == 1select d;
DEMO
OrderOrderrID <pk>
OrderDetailOriderDetailID<pk>OrderD <fk>
Order maps reference to collection of Order Details objects (EntitySet Type)
Order Details maps reference to single Order object (EntityRef Type)
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
DEMO
Projection
Rob Vettor28
Parameterized Queries vs. Sprocs
Rob Vettor 29
LINQ fully supports both approaches
Parameterized queries
Good for CRUD operations
Executions plans are cached and reused
Automatically generated by LINQ framework
Do require server permissions at the table level
Stored Procedures
More complex business logic (beyond CRUD)
Security, performance, auditing
Deferred Loading
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 where c.Region == "OR" orderby c.CompanyName select c;
//-- Then, execute query gvQuery.DataSource = query; 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
Define query and storein variable
Execute query when absolutely necessary
Eager Loading
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()
Include() method supports eager execution:
Retrieves parent and child entities immediately, not when referenced
(No Demo Yet)
Rob Vettor 31
Loading Single Objects
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
DEMO NOW!
Rob Vettor 32
Loading Object Graphs
Object Graph: Set of individual, but related objects, that together form a logical whole unit
By default, with deferred execution, child objects load one at a time (separate data store call for each) as needed.
We can use Include() method to predefine the object graph, forcing all entire graph to load at once with single query
DEMO Load object graph including Orders, Order Details and Products
Rob Vettor 33
Customer ProductOrder CategoryOrder Detail
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
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
Updates/Change Tracking
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;
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
Inserts
Rob Vettor 37
Inserting with EF is multi-step process Create new (disconnected) entity object and populate Attach new entity to the ObjectContext Call SaveChanges() to commit to database
Next DEMO
Show how ObjectContext leverages inferred relationship Inserts both parent and child records in correct order Maintains foreign key relationship Automatically manages the identity values
Show that ObjectContext automatically returns new identity key and assigns to new entity objects
The Problem
The EF and EDM
Mapping a Conceptual Model
Programming a Conceptual Model
Key Concepts
EF vs. L2S… Advanced Mapping
How to get started
Rob Vettor 38
Agenda
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
LTS later moved to the Data Team 11/08, Data Team announced invest in EF, while
maintaining and tweaking L2S Microsoft will provide migration path to EF
and recommend EF over LTS
History
Rob Vettor39
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
How They Differ
Rob Vettor40
EF vs. LTS
Rob Vettor 41
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
Development Time rapid developmentslower development but
more capabilities
Mapping Direct 1-to-1 Custom mapping
Inheritance hard to apply simple to apply
Support ? $$$, resources, innovation
The Problem
The EF and EDM
Mapping a Conceptual Model
Programming a Conceptual Model
Some Intermediate Topics
EF vs. L2S
Advanced Mapping… How to get started
Rob Vettor 42
Agenda
Advanced EDM Mapping
EDM provides flexibility customizing conceptual model
Most customizations occur in the conceptual model and depend on the mapping layer to map to underlying store
Designer supports following customization: Table Per Hierarchy Inheritance mapping
Table Per Type Inheritance mapping
Entity (vertical) splitting
Rob Vettor 43
Rob Vettor 44
Con. Schema.csdl File
Mapping.msl File
Storage Schema.ssdl File
Contact
Employee
SalesPerson
SalesOrder
Logical Schema
SalesPeople
SalesOrder
StoreOrder
Conceptual Schema
Mapping Between Layers
Table Per Type Inheritance
Table Per Hierarchy Inheritance
Table-Per-Hierarchy Mapping (TPH)
Rob Vettor 45
Simple inheritance that maps multiple entities to single database table
Mapping conditionally based on discriminator column to differentiate records as different types
Quick to implement, but lacks scalability – derived from single database table
No Demo Yet
Employee
managementFlag
Database Table
EntitiesDiscriminator
Column
ManagementEmployee
Employee
Base Type
Derived Type
Using TPH
Discriminator column identifies whether row belongs to base or derived type
Can include additional columns for derived type whose value is NULL for base type (denormalized!)
Can query on derived types without a where clause by using OfType() method from c in ctx.Customers.OfType<ManagementEmployees>()
Show in Designer Demo
Limitations
Difficult to update discriminator column value via EF – must use database construct (trigger/stored proc)
Rob Vettor 46
Table-Per-Type Mapping
Rob Vettor 47
Inheritance spanning related database tables.
Exposes attributes from both parent table and child table into single derived entity
Defined in database with separate tables where one table (child) describes new type based on another table (parent)
No Demo Yet
Tax Audit
CustomersUSA
Database Table Entities
State Tax Audit
Customers
Using TPT
Eliminates need to programmatically traverse navigation properties to move from child (CustUSA) to parent (Cust) to include parent information
When projecting on derived type, use OfType() method from c in ctx.Customers.OfType<CustomersUSA>()
Show in Designer, Demo
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
Entity (Vertical) Splitting Map single entity to multiple tables Tables must share common key Typically for 1-to-1 relationships where one table provide
additional information about another
No Demo Yet
Rob Vettor 49
Employee
Employee
Database Tables
Entities
EmployeePersonal
EmployeeFinancial
Using Entity (Vertical) Splitting
Rob Vettor 50
Vertical Entity Partitioning Addresses data modeling practice of decomposing large
table into number of smaller tables Relives you from having to traverse navigation properties
among the tables to retrieve data In mapping details window, we map single entity to three
underlying tables Conceptual model contains single product entity Store (SSDL) contains three product tables MSL metadata maps single entity to multiple tables
Show Mapping Details in Designer; Demo
Advanced EDM Mapping
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
The Mapping Detail Tool enables you to map your customizations to your underlying data store layer
Designer supports most, but not all, customization Table Per Hierarchy Inheritance mapping
Table Per Type Inheritance mapping
Entity (vertical) splitting
Rob Vettor 51
The Problem
The EF and EDM
Mapping a Conceptual Model
Programming a Conceptual Model
Key Concepts
EF vs. L2S
Advanced Mapping
Getting Started…
Rob Vettor 52
Agenda
EF Books
Rob Vettor 53
Mike Taulty 150 Screen Casts
EF Webcasts
Rob Vettor 54
Rob Vettor 55
Questions?Questions?Comments?Comments?
Suggestions?Suggestions?
Questions?Questions?Comments?Comments?
Suggestions?Suggestions?
http://weblogs.asp.net/dotnetarchitect