Your SlideShare is downloading. ×
Getting started with entity framework revised 9 09
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Getting started with entity framework revised 9 09

974
views

Published on

Published in: Technology

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
974
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
27
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • 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.
  • Transcript

    • 1. Entity Framework@ 5,000 Feet Rob Vettor , C# MVP robvettor@hotmail.comRob Vettor 1
    • 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-consumingRob 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-consumingRob 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 moreRob Vettor 6
    • 7. Autobiographical Stuff… Architect/Team Lead C# MVP INETA Regional Speaker Frequent Presenter User Group Leader Developer Guidance Council memberRob 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 ServicesRob Vettor 9
    • 10. Agendas Define Entity Frameworks Explore its Architectures Map Conceptual Models Program Conceptual Models Examine Key Conceptss Compare EF vs. L2Ss 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 RelationalRob 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 CommandRob Vettor 14
    • 15. Architectural Layering Object Services Entity Client Core EDM of EF 15Rob Vettor
    • 16. Entity Data Models 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 ModelDatabase UI OO Servicess Abstracts developer from a model pleasing to a DBA (normalized, maintainable, efficient, secure), but complicated to program against Rob Vettor 16
    • 17. Summarys Entity Framework is data access framework that bridges gap between data and objectss Sits beneath many of Microsoft’s new offerings: ADODS, Azure Tables, RIA Servicess Automatically creates entity objects and mappingss Transforms LINQ Queries into SQLs Delivers flexible object model that enables you to map data to objects as you likeRob Vettor 17
    • 18. Agendas The Problems The EF and EDMsMapping a Conceptual Model…s Programming a Conceptual Models Key Concepts…s EF vs. L2Ss Advanced Mappings How to get startedRob Vettor 18
    • 19. Map Conceptual Models 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 classess End up with object-representation of our data stores DEMORob 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 identityRob Vettor 20
    • 21. Agendas The Problems The EF and EDMs Mapping a Conceptual ModelsProgramming a Conceptual Model…s Key Conceptss EF vs. L2Ss Advanced Mappings How to get startedRob 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” entitiesRob Vettor 22
    • 23. Two Simple Demoss eSQL Demo… and LINQ-To-Entities Demo…  Query customers from our conceptual model  Return all customers in Oregon  Render in GridViews View generated SQL in SQL Profilers Demonstrate “Query Syntax” vs. “Method Syntax”s Remember: We are querying conceptual model, not data storeRob Vettor 23
    • 24. Agendas The Problems The EF and EDMs Mapping a Conceptual Models Programming a Conceptual ModelsKey Concepts…s EF vs. L2Ss Advanced Mappings How to get startedRob 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 Propertiess 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. Projections 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 expressionsDEMO 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, auditingRob 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.CompanyNameDefine 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 Loadings 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 referenceds (No Demo Yet)Rob Vettor 31
    • 32. Loading Single Objectss 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 DBs DEMO NOW!Rob Vettor 32
    • 33. Loading Object Graphss Object Graph: Set of individual, but related objects, that together form a logical whole unit Customer Order Order Detail Product Categorys 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 querys DEMO  Load object graph including Orders, Order Details and ProductsRob 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 queryRob 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 Trackings 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 transactionRob 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 objectsRob Vettor 37
    • 38. Agendas The Problems The EF and EDMs Mapping a Conceptual Models Programming a Conceptual Models Key ConceptssEF vs. L2S…s Advanced Mappings How to get startedRob Vettor 38
    • 39. Historys 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 objectss LTS later moved to the Data Teams 11/08, Data Team announced invest in EF, while maintaining and tweaking L2Ss Microsoft will provide migration path to EF and recommend EF over LTS 39
    • 40. How They Differs 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 ManyComplexity/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. Agendas The Problems The EF and EDMs Mapping a Conceptual Models Programming a Conceptual Models Some Intermediate Topicss EF vs. L2SsAdvanced Mapping…s How to get startedRob Vettor 42
    • 43. Advanced EDM Mappings EDM provides flexibility customizing conceptual models Most customizations occur in the conceptual model and depend on the mapping layer to map to underlying stores Designer supports following customization:  Table Per Hierarchy Inheritance mapping  Table Per Type Inheritance mapping  Entity (vertical) splittingRob 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 FileRob Vettor 44
    • 45. Table-Per-Hierarchy Mapping (TPH)s Simple inheritance that maps multiple entities to single database tables Mapping conditionally based on discriminator column to differentiate records as different typess Quick to implement, but lacks scalability – derived from single database table Base Type Entities Discriminator Column Database Table Employee Employee managementFlag ManagementEmployees No Demo Yet Derived Type Rob Vettor 45
    • 46. Using TPHs Discriminator column identifies whether row belongs to base or derived types 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 Designers Demos Limitations  Difficult to update discriminator column value via EF – must use database construct (trigger/stored proc)Rob Vettor 46
    • 47. Table-Per-Type Mappings Inheritance spanning related database tables.s Exposes attributes from both parent table and child table into single derived entitys 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 CustomersUSAs No Demo Yet Rob Vettor 47
    • 48. Using TPTs Eliminates need to programmatically traverse navigation properties to move from child (CustUSA) to parent (Cust) to include parent informations When projecting on derived type, use OfType() method  from c in ctx.Customers.OfType<CustomersUSA>()s Show in Designer, Demos 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 CustomerUSARob Vettor 48
    • 49. Entity (Vertical) Splittings Map single entity to multiple tabless Tables must share common keys Typically for 1-to-1 relationships where one table provide additional information about another Database Tables Employee Entities EmployeeFinancial Employee EmployeePersonals No Demo YetRob Vettor 49
    • 50. Using Entity (Vertical) Splittings 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 Mappings 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 creates The Mapping Detail Tool enables you to map your customizations to your underlying data store layers Designer supports most, but not all, customization  Table Per Hierarchy Inheritance mapping  Table Per Type Inheritance mapping  Entity (vertical) splittingRob Vettor 51
    • 52. Agendas The Problems The EF and EDMs Mapping a Conceptual Models Programming a Conceptual Models Key Conceptss EF vs. L2Ss Advanced MappingsGetting Started…Rob Vettor 52
    • 53. EF BooksRob Vettor 53
    • 54. EF Webcastss Mike Taulty  150 Screen CastsRob Vettor 54
    • 55. Questions? Comments? Suggestions? robvettor@hotmail.com http://weblogs.asp.net/dotnetarchitectRob Vettor 55