1、ADO.NET Entity Framework, Jos A. BlakeleyPartner ArchitectMicrosoft Corporation, Michael PizzoPrincipal ArchitectMicrosoft Corporation,10-12:00 Section 1: Evolution of ADO.NET 12:00-1:15 1:15-2:30 Section 2: ADO.NET and LINQ 2:30-2:45 2:45-4:00 Section 3: ADO.NET Entity Framework Deep Dive 4:00-4:15
2、 4:15-5:45 Section 4: Building on ADO.NET,ADO.NET A to Z: Agenda,Evolution of Data Access APIs Proprietary APIs Object Databases Standard SQL Data Access APIs ODBC, DAO, RDO Componentized Data Access OLE DB, ADO .NET Data Access ADO.NET ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framewo
3、rk,Section 1: Evolution of ADO.NET,Application-specific, monolithic data access Files, hierarchical DBMSs CICS, IMS, etc. Relational DBMSs emerged DBMS-specific APIs and protocols OCI, DBLIB, SQL*, TDS, DRDA Embedded SQL 1xN data access problem Each app writes data-source-neutral data access layer,P
4、roprietary APIs 70s & early 80s,ODBC Common C API for accessing SQL Databases Driver Manager loads DBMS-specific drivers Developed with SQL Access Group, ANSI/ISO Adopted as SQL-CLI Addendum to SQL92 DAO “OLE Automation“ interface to Microsoft Access Provided Access, VB developers access to ODBC sou
5、rces RDO DAO-style interfaces directly over ODBC Subsumed by DAO “ODBC Direct“ mode,SQL APIs Late 80s & early 90s,Transparent Language Persistence C+, Lisp, SmallTalk Transaction support - low throughput Very transparent persistence Fast navigational performance Object graph loaded to memory Most na
6、vigation in memory Object faulting based on memory mapped IO and pointer swizzling Limited query support ODMG OQL standard No efficient implementations Limited indexing support Limited customer acceptance,Object Databases Mid 90s,OLE DB COM-Based Data Access API Relational and non-relational sources
7、 Tables, hierarchies, OLAP, documents Factored interfaces Providers: SQL, ISAM, Excel, AS400 FS, Exchange Services: cursor engine, shaping, remoting, resource pooling, transaction enlistment Used by SQL Server internally and externally SQL Engine, Federated Query, Integration Services, ADO “OLE Auto
8、mation“ interface for OLE DB Interface for VB developers Similar programming model to DAO Introduced disconnected RecordSets,Component Data Access Late 90s,Need a managed API for the new .NET Framework Consistency across framework Explicit separation of connected access from disconnected Connected M
9、odel Lower-level, common API for exposing the functionality native to a data store Higher level abstractions, common functionality built on top Dataset as “in-memory data cache“ Database independent Predictable semantics, latency, error handling, Combine data from multiple sources Support for XML,AD
10、O.NET 1.0 Early 00s,Evolution of Data Access APIs ADO.NET 1.0 Architecture Getting Data from a SQL Database Working with Data ADO.NET and XML Building a Data Platform The ADO.NET Entity Framework,Section 1: Evolution of ADO.NET,ADO.NET 1.0 Architecture,OLTP operations, Programmatic Processing, Frame
11、works,Getting Data From a SQL Database ADO.NET Data Provider,Specific to a particular DBMS Directly exposes consumer interfaces No more COM/Automation dichotomy ADO.NET DataProvider Object Model Connection Establishes connection to DataSource Transaction Explicit Transaction Control Command Execute
12、SQL statement DataReader Forward-only, Read-Only Result Stream Fields accessed through strongly typed, indexed accessors,Relational View of Data Tables, Columns, Rows, Constraints, Relations Directly create metadata and insert data Explicit Disconnected Model Disconnected, remotable object No knowle
13、dge of data source or properties Common Behavior Predictable performance characteristics Array-like indexing Strong Typing,Working with Data DataSet,DataSet Scenarios,Application Data Remoting Results SOAP, WebMethods, Remoting Caching Results ASP.NET Cache Persisting results Save Data as XML, Schem
14、a as XSD User interaction Scrolling, sorting, filtering DataView, DataViewManager Binding Windows controls,DataAdapter,Loads a table from a data store and writes changes back. Exposes two methods: Fill(DataSet,DataTable) Update(DataSet,DataTable) Provides mappings between tables & columns User provi
15、des insert/update/delete commands Allows use of Stored Procedures CommandBuilder component available Allows single DataSet to be populated from multiple different datasources,Data store,DataAdapter,InsertCommand,UpdateCommand,DeleteCommand,SelectCommand,Fill(),Update(),DataSet,ADO.NET and XML,The Da
16、taSet Loads/saves XML data into/out of DataSet Schema can be loaded/saved as XSD Schema can be inferred from XML Data The DataSet can be associated with an XmlDataDocument Exposes a relational view over structured XML According to the DataSet schema Allows strong typing, control binding, relational
17、access of XML data Allows XML tools (schema validation, XSL/T, XPath queries) against relational data Preserves full fidelity of XML Document,ADO.NET 1.0,demo,Evolution of Data Access APIs ADO.NET 1.0 Building a Data Platform Why a Conceptual Model? The Microsoft Entity Data Model Entity SQL The ADO
18、.NET Entity Framework,Section 1: Evolution of ADO.NET,Writing queries is difficult No help from compiler Results are untyped rectangular records Database Schemas optimized for storage concerns Relational Tables contain flat, homogenous records Implicit Logic Embedded in Application Brittle, Hard to
19、maintain Lack of common syntax across relational databases,The Problem Programming Data is Hard,Rapid Development Strongly typed queries Strongly typed results with Business Logic Lower TCO Work with an explicit data model Types, Inheritance, Relationships, Complex Properties, Decouple application f
20、rom storage schema Better Portability Common query language across disparate sources,The Opportunity Increase Developer Productivity,Applications Today Implicitly Contain the Data Model Logic and Model Intertwined Conceptual Mismatch Often encapsulate in a “Data Access Layer“,Wheres Your Data Model?
21、,Applications Today Implicitly Contain the Data Model Logic and Model Intertwined Conceptual Mismatch Often encapsulate in a “Data Access Layer“,Wheres Your Data Model?,The Need Applications work with a well Defined Model Storage Schema Abstraction Declarative mapping between application and storage
22、 models No brittle, hard-coded mapping,An extended relational model with Entity-Relationship Model concepts Entity Types Strong type with Identity Inheritance Scalar/Complex properties EntitySets Hold instances of Entity Types Similar to relational tables Can have multiple Entitysets of the same Ent
23、ityTypes Relationships (“Associations“) Named relationships between Entities 01:*, 01:01, 1:1, 1:M, M:N Navigation may be exposed as NavigationProperties on EntityTypes AssociationSets Contains instances of associations May be queried directly EntityContainers Contains EntitySets, AssociationSets,Th
24、e Microsoft Entity Data Model,1,1,N,SQL extended to support the Entity Model SELECT Value Promotes a single column to the record Entity construction Useful in DefiningQueries Type Operations OFTYPE, TREAT, Relationship Navigation Navigate(), . Manipulation of Keys Key(), Ref()/DeRef(), CreateRef, Ro
25、w() Other Set()/Flatten() CrossApply, OuterApply Skip/Limit,EntitySQL,Data Access in the 80s ADO.NET 1.0 Building a Data Platform ADO.NET Entity Framework Introduction Overview Entity Designer EntityClient Object Services,Section 1: Evolution of ADO.NET,ADO.NET Entity Framework,Data Access in the 80
26、s ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framework Overview Entity Designer EntityClient Object Services,Section 1: Evolution of ADO.NET,Define / Modify Conceptual Entity Model Define Entities, Associations, Functions Create from scratch or Reverse-Engineer from database Define mapp
27、ing to Relational Store Generate/Refresh storage schema definition from Database Generate CLR Objects for Entity Model Partial classes Generate runtime metadata .csdl, .msl, .ssdl files or embed as resources,Entity Designer,No support for: “Model-First“ Complex Types Abstract Types Multiple Entity S
28、ets per Type Practical limitation of 120 Entities No design support for SSDL Must manually edit XML Refresh overwrites manual changes to SSDL Lack of Automatic Pluralization support Modify EntitySet names in model,Entity Designer V1 Limitations,Entity Designer,demo,Data Access in the 80s ADO.NET 1.0
29、 Building a Data Platform The ADO.NET Entity Framework Overview Entity Designer EntityClient Object Services,Section 1: Evolution of ADO.NET,is an ADO.NET Data Provider EntityConnection Metadata/Mapping specified in ConnectionString Can also load from XmlReader EntityCommand Canonical EntitySQL synt
30、ax Stored Procedure Support Access to Provider-specific SQL EntityDataReader Rectangular results described through IDataReader Typing, Polymorphism described through IExtendedDataReader Limitations No DML, DDL Call Functions in SSDL No DataAdapter,EntityClient,EntityClient,demo,Data Access in the 80
31、s ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framework Overview Entity Designer EntityClient Object Services,Section 1: Evolution of ADO.NET,Object Services,Provides core object service abstractions Context, identity, state management Query, object materialization ObjectContext, ObjectQ
32、uery, ObjectStateManager Tools generate partial classes from EDM models Strongly typed collections Navigational patterns, relationship fix up Users can extend the partial classes to add business logic Provides query and update interfaces LINQ integration, Entity SQL Strongly typed CRUD operations (a
33、dd, delete, savechanges),Object Services,demo,Questions?,Introduction to LINQ LINQ to SQL LINQ to Entities LINQ to DataSet,Section 2: ADO.NET and LINQ,Queries as first-class concept in .NET languages Builds on several language features Type inference, Delegates, Generics Enabled by Lambda expression
34、s Anonymous types Object initialization expressions Extension methods Query expressions,Introduction to LINQ,Introduction to LINQ,/ Lambda Expressions string names = “Luis“, “Mary“, “Mike“, “Jose“ ; Display( names, s = s.Length 3);/ Anonymous Types and object initialization var emp = new Name = “Mar
35、y“, Company = “Microsoft“, Age = 30 ; / Extension Methods public static class ExtensionMethods public static void Display(this T names, Func filter) foreach (T s in names) if (filter(s) Console.WriteLine(s); / Query Expressions var query = from c in Customerswhere c.Discount = 3.0 ,Introduction to L
36、INQ LINQ to SQL Design Points Features Demo LINQ to Entities LINQ to DataSet,Section 2: ADO.NET and LINQ,Direct Mapping Each class maps to a single SQL Schema Object Table, View Stored Procedure, Table Valued Function Simple renaming of Tables, Columns Foreign Keys can be expressed as Relationships
37、Properties to navigate in query, results Inheritance Multiple Classes in a Hierarchy can map to a single Table/View/Stored Proc/TVF with a discriminator column,LINQ to SQL Direct Mapping,LINQ to SQL Strongly typed SQL Database,Design Points Rapid Development against SQL Database Direct Mapping to SQ
38、L Server Schema Mappings expressed in Attributes or XML file “Just Work“ for common scenarios Execute when needed Naming Conventions Business Logic Custom Insert/Update/Delete operations Minimally Intrusive object model Provide Customization, Optimizations where required Targets: Microsoft SQL Serve
39、r,Customization Business Logic Partial classes for generated Objects Add Methods, non-persistent members, etc. Business Logic through Partial methods based on naming conventions Update Logic Implement partial methods in derived Class Call Stored Procedures or invoke custom logic Optimizations Loadin
40、g Options “Span“ related information ObjectTrackingEnabled DeferredLoadingEnabled Compiled Query Save overhead of SQL generation from Language Expression LinqDataSource for use in ASP.NET,LINQ to SQL Features,LINQ to SQL,demo,Introduction to LINQ LINQ to SQL LINQ to Entities Design Points Features D
41、emo LINQ to DataSet,Section 2: ADO.NET and LINQ,LINQ to Entities Flexible Mapping to Relational Data,Design Points Flexible Mapping to Existing Relational Schema Well defined Conceptual model Share common model across products (Reporting, Analysis, etc) Declarative Mapping between Application and St
42、ore Allows Storage Schema and Application to evolve independently Explicit Operations Server interactions should be explicit Build implicit logic on top of explicit operations Targets: Microsoft SQL Server and third-party databases,LINQ to Entities Features,Customization Business Logic Partial Class
43、es, Events, Partial Methods Update Logic Generated Update Views Declarative stored procedures Optimizations “Span“ related members NoTracking Extensibility Partitioning of Metadata Flexible Runtime Mapping Metadata Pluggability EntityDataSource for use from ASP.NET,LINQ to Entities,demo,Introduction
44、 to LINQ LINQ to SQL LINQ to Entities LINQ to DataSet,Section 2: ADO.NET and LINQ,LINQ to DataSet LINQ over Disconnected Cache with Change Tracking,Disconnected Cache Offline/Remote Data Aggregation Application Data All with Change Tracking Queryable Filter, Projection Joins Across Tables Other in-M
45、emory sources Local expressions All through Common LINQ syntax,LINQ to DataSet Typed and UnTyped,Untyped DataSet Call AsEnumerable() on DataTable Reference Fields by Name Use Field(columnName) Project out fields for strongly typed result,var query = from row in myDataSet.Tables“Customers“.AsEnumerab
46、le()where row .Field(“City“) = “London“ select new row.Field (“CustomerID“),row.Field (“ContactName“) ;,var query = from customer in northwind.Customerswhere customer.City = “London“ select customer;,Typed DataSetUse strongly typed accessors,LINQ to DataSet,demo,LINQ to SQL Strongly Typed Database E
47、mphasis on rapid application development Direct mapping to Microsoft SQL Server family of databases LINQ to Entities Flexible mapping to existing Schema Focus on enterprise-grade data scenarios Flexible Mapping to Microsoft SQL Server and third-party databases LINQ to DataSet In-Memory Cache w/Chang
48、e Tracking All the scenarios where DataSet is useful today Offline, Disconnected, Aggregation Change Tracking Plus support for Query Operations Strongly typed or Untyped DataSet Support,Summary: ADO.NET and LINQ,Questions?,Customizing Data Classes Entity Framework Mapping Scenarios Database Design C
49、onsiderations Advanced Mapping Techniques,Section 3: ADO.NET Entity Framework Deep Dive,Partial Classes Add business logic, methods, non-persisted properties to partial classes Codegen Customization Add custom logic to Property, Type Generation Attributes, Interfaces, Members, BaseClass, Getters, Setters, BackingField, Return Type, Custom Classes Write your own classes that Derive from EntityObject, or Implement interfaces: IEntityWithKey, IEntityWithChangeTracker, IEntityWithRelationships,Customizing Data Classes,