1. Trang chủ
  2. » Công Nghệ Thông Tin

Oreilly programming entity framework 2nd edition aug 2010

914 136 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 914
Dung lượng 10,59 MB

Nội dung

Download from Library of Wow! eBook Download from Library of Wow! eBook SECOND EDITION Programming Entity Framework Julia Lerman Beijing • Cambridge • Farnham • Kưln • Sebastopol • Taipei • Tokyo Download from Library of Wow! eBook Programming Entity Framework, Second Edition by Julia Lerman Copyright © 2010 Julia Lerman All rights reserved Printed in the United States of America Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://my.safaribooksonline.com) For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com Editors: Mike Hendrickson and Laurel Ruma Production Editor: Loranah Dimant Copyeditor: Audrey Doyle Proofreader: Sada Preisch Indexer: Ellen Troutman Zaig Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: February 2009: August 2010: First Edition Second Edition Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc Programming Entity Framework, the image of a Seychelles blue pigeon, and related trade dress are trademarks of O’Reilly Media, Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps .NET is a registered trademark of Microsoft Corporation While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein ISBN: 978-0-596-80726-9 [SB] 1281106344 Download from Library of Wow! eBook Table of Contents Foreword xxi Preface xxiii Introducing the ADO.NET Entity Framework The Entity Relationship Model: Programming Against a Model, Not the Database The Entity Data Model: A Client-Side Data Model Entities: Blueprints for Business Classes The Backend Database: Your Choice Database Providers Access and ODBC Entity Framework Features: APIs and Tools Metadata Entity Data Model Design Tools Object Services POCO Support Change Tracking Relationship Management and Foreign Keys Data Binding n-Tier Development EntityClient The Entity Framework and WCF Services What About ADO.NET DataSets and LINQ to SQL? DataSets LINQ to SQL Entity Framework Pain Points Are Fading Away Programming the Entity Framework 9 10 10 11 12 12 13 13 14 14 15 15 15 16 16 17 Exploring the Entity Data Model 19 Why Use an Entity Data Model? 19 iii Download from Library of Wow! eBook The EDM Within the Entity Framework Walkthrough: Building Your First EDM Inspecting the EDM in the Designer Window Entity Container Properties Entity Properties Entity Property Properties The Model’s Supporting Metadata Viewing the Model in the Model Browser Viewing the Model’s Raw XML CSDL: The Conceptual Schema EntityContainer EntitySet EntityType Associations Navigation Property Navigation Properties That Return Collections SSDL: The Store Schema MSL: The Mappings Database Views in the EDM Summary 20 21 24 26 26 27 29 31 31 33 34 35 36 38 41 42 43 45 46 47 Querying Entity Data Models 49 Query the Model, Not the Database Your First EDM Query Where Did the Context and Classes Come From? Querying with LINQ to Entities Writing Your First LINQ to Entities Query Querying with Object Services and Entity SQL Why Another Way to Query? Entity SQL The Parameterized ObjectQuery Querying with Methods Querying with LINQ Methods Querying with Query Builder Methods and Entity SQL The Shortest Query ObjectQuery, ObjectSet, and LINQ to Entities Querying with EntityClient to Return Streamed Data EntityConnection and the Connection String EntityCommand ExecuteReader Forward-Only Access to the Fields Translating Entity Queries to Database Queries Pay Attention to the NET Method’s Impact on Generated SQL iv | Table of Contents Download from Library of Wow! eBook 49 50 51 55 55 57 57 58 60 61 61 64 66 66 68 70 71 71 71 71 72 Avoiding Inadvertent Query Execution Summary 74 75 Exploring LINQ to Entities in Greater Depth 77 Getting Ready with Some New Lingo Projections in Queries Projections in LINQ to Entities VB and C# Syntax Differences LINQ Projections and Special Language Features Projections with LINQ Query Methods Using Navigations in Queries Navigating to an EntityReference Filtering and Sorting with an EntityReference Navigating to Entity Collections Projecting Properties from EntityCollection Entities Filtering and Sorting with EntityCollections Aggregates with EntityCollections Aggregates in LINQ Methods Joins and Nested Queries Joins Nested Queries Grouping Naming Properties When Grouping Chaining Aggregates Filtering on Group Conditions Shaping Data Returned by Queries Limiting Which Related Data Is Returned Loading Related Data Controlling Lazy Loading Explicitly Loading Entity Collections and Entity References Using the Include Method to Eager-Load Pros and Cons of Load and Include Retrieving a Single Entity Retrieving a Single Entity with GetObjectByKey Finding More Query Samples Summary 78 78 79 79 80 84 84 84 86 86 87 88 88 89 90 90 91 93 94 95 95 97 99 100 101 101 103 106 107 108 109 109 Exploring Entity SQL in Greater Depth 111 Literals in Entity SQL Expressing a DateTime Literal Expressing a Decimal Literal Using Additional Literal Types Projecting in Entity SQL 111 112 112 112 113 Table of Contents | v Download from Library of Wow! eBook DbDataRecords and Nonscalar Properties Projecting with Query Builder Methods Using Navigation in Entity SQL Queries Navigating to an EntityReference Filtering and Sorting with an EntityReference Filtering and Sorting with EntityCollections Aggregating with EntityCollections Using Entity SQL SET Operators Aggregating with Query Builder Methods Using Joins Nesting Queries Grouping in Entity SQL Returning Entities from an Entity SQL GROUP BY Query Filtering Based on Group Properties Shaping Data with Entity SQL Using Include with an ObjectQuery and Entity SQL Understanding Entity SQL’s Wrapped and Unwrapped Results Entity SQL Rules for Wrapped and Unwrapped Results Digging a Little Deeper into EntityClient’s Results Summary 114 115 115 115 116 116 117 117 118 118 119 120 121 121 122 123 124 126 126 127 Modifying Entities and Saving Changes 129 Keeping Track of Entities Managing an Entity’s State Saving Changes Back to the Database Inserting New Objects Inserting New Parents and Children Deleting Entities Summary 129 130 131 134 135 137 139 Using Stored Procedures with the EDM 141 Updating the Model from a Database Working with Functions Function Attributes Mapping Functions to Entities Mapping Insert, Update, and Delete Functions to an Entity Inspecting Mappings in XML Using Mapped Functions Using the EDM Designer Model Browser to Import Additional Functions into Your Model Mapping the First of the Read Stored Procedures: ContactsbyState Using Imported Functions Avoiding Inadvertent Client-Side Processing vi | Table of Contents Download from Library of Wow! eBook 142 143 144 146 148 152 153 155 156 158 159 Mapping a Function to a Scalar Type Mapping a Function to a Complex Type Summary 159 160 163 Implementing a More Real-World Model 165 Introducing the BreakAway Geek Adventures Business Model and Legacy Database Creating a Separate Project for an EDM Inspecting and Cleaning Up a New EDM Modifying the Names of Entities and Properties Resolving Collisions Between Property Names and Entity Names Cleaning Up Navigation Property Names Setting Default Values Mapping Stored Procedures Using the Use Original Value Checkbox in Update Mappings Working with Many-to-Many Relationships Inspecting the Completed BreakAway Model Building the BreakAway Model Assembly Looking at the Compiled Assembly Splitting Out the Model’s Metadata Files Summary 166 168 168 170 172 172 174 175 176 178 181 182 183 184 185 Data Binding with Windows Forms and WPF Applications 187 Data Binding with Windows Forms Applications Creating a Windows Forms Application Using Windows Forms Data Sources Creating an Object Data Source for a Customer Entity Getting an Entity’s Details onto a Form Adding Code to Query an EDM When a Form Loads Binding Without a BindingSource Adding an EntityCollection to the Form Displaying the Properties of Related Data in the Grid Allowing Users to Edit Data Editing Navigation Properties (and Shrinking the Query) Replacing the Navigation Property TextBoxes with ComboBoxes Adding New Customers Deleting Reservations Data Binding with WPF Applications Creating the WPF Form Creating the WPF Project Adding the Necessary Data Source Objects Inspecting the XAML and Code Generated by the Automated Data Binding 187 188 189 190 191 194 196 198 199 201 202 204 208 211 213 213 214 215 215 Table of Contents | vii Download from Library of Wow! eBook Adding Code to Query the EDM When the Window Loads Customizing the Display of the Controls Selecting an Entity and Viewing Its Details Adding Another EntityCollection to the Mix Editing Entities and Their Related Data Using SortDescriptions to Keep Sorting in Sync with Data Modifications Adding Items to the Child EntityCollection The Last Task: Adding New Trips to the Catalog Summary 216 218 219 222 224 225 226 227 230 10 Working with Object Services 231 Where Does Object Services Fit into the Framework? Processing Queries Parsing Queries: From Query to Command Tree to SQL Understanding Query Builder Methods Analyzing a Query with ObjectQuery Methods and Properties Executing Queries with ToList, ToArray, First or Single Executing Queries with the Execute Method Overriding a Default Connection with ObjectContext.Connection Handling Command Execution with EntityClient Materializing Objects Managing Object State Using EntityKey to Manage Objects Merging Results into the Cache with MergeOptions Inspecting ObjectStateEntry Maintaining EntityState Managing Relationships Attaching and Detaching Objects from the ObjectContext Taking Control of ObjectState ObjectStateManager Methods ObjectStateEntry State Methods for Managing State ObjectSet State Methods Sending Changes Back to the Database ObjectContext.SaveChanges Affecting SaveChanges Default Behavior Overriding SaveChanges Completely Data Validation with the SavingChanges Event Concurrency Management Transaction Support Implementing Serialization, Data Binding, and More Object Services Supports XML and Binary Serialization Object Services Supports Data Binding viii | Table of Contents Download from Library of Wow! eBook 231 233 234 235 238 241 242 242 244 244 246 246 247 248 249 252 253 257 257 258 259 259 259 260 261 261 261 262 263 263 265 reading for ObjectStateEntry, 613 OritinalValues property, 566 ORM (Object Relational Mapping), limitations of Entity Framework, 17 Out parameters, 145 Overridable keyword, 346 P Page events, 327 Page objects, 784 paging, 301 parallel computing in NET 4, 596 Parameter element, 145 parameterized queries with ObjectQuery, 60 Parameters property, ObjectQuery class, 241 ParameterTypeSemantics attribute, 145 partial classes, 267 additional uses of, 290 creating and naming files for, 268 declaring additions to, 268 for POCOs, 714 partial methods, 269–274 creating your own, 284 overloading entity creation methods, 290 overriding object constructor, 284 inserting managed partial method in entity classes, 293 OnContextCreated, 269 On[Property]Changed and On[Property]Changing, 271 pass-through queries, 424–426 ExecuteStoreCommand method, 440 ExecuteStoreQuery method, 424–426 performance tuning, 574–591 caching for Entity SQL queries, 580 code used to measure query performance, 577–579 guidance from Entity Framework team member, 590 measuring query performance, 575 measuring startup performance, 579 precompiling LINQ to Entities queries, 585 precompiling views, 582 reducing cost of query compilation, 580 updates, 589 PersistedStateEntry class, 681 persistent entities versus using independent values, 788 persistent ignorant entities, creating, 694–714 building interface for repository classes, 702 building interface to represent context, 698 creating repository classes, 703–706 fake context class, 708 fake ObjectSet class, 710–712 modifying ObjectContext class to implement interface, 699–702 moving POCOs to own project, 695 starting with model and POCO entities, 697 testing method against database, 707 PLINQ (Parallel LINQ), 596 POCO (Plain Old CLR Objects) support, 12, 248 POCO entities rules for getting proxy behavior with, 349 TPT inheritance, 366 using proxies to enable change notification, 346 POCO Entity Generator, 350 POCOs (Plain Old CLR Objects), 335–359, 489, 521 adding validation logic to POCO classes, 714 change tracking with, 341 creating classes for persistent ignorant entities, 697 creating classes for WCF services, 490–497 adding custom logic with base class, 493 following WCF collection rules, 495 isolating POCO entities in own project, 491 preventing marking of properties as virtual, 496 updating classes for current model, 490 creating model to work with preexisting classes, 358 creating ObjectContext class to manage, 339–340 creating POCO classes, 336–339 entities in layered client-side applications, 778–782 providing EntityState, 779 862 | Index Download from Library of Wow! eBook providing logic in place of other EntityObject behavior, 781 impact on two-way relationships, 342–345 loading related data with, 341 moving POCO classes to own project, 695 POCO entities versus EntityObjecs in WCF services, 519 relationship management in POCO entities, 537 testing interaction with ObjectContext, 686 using Entity Framework with no model, 359 using POCO classes with WCF services, 452 using POCO entities with WCF Data and RIA Services, 515 POCO entities in RIA services, 517–519 preparing for WCF Data Services, 515 using proxies for change notification, lazy loading and to fix relationships, 345–350 using T4 to generate classes, 350–354 WCF service that uses POCO classes, 497– 503 implementing the interface, 498–500 using the service, 500–503 pooling connections, 563 Power Pack (Database Generation), 747 precompilation, 97 precompiling queries (see compilation) predicates, 63 pregenerating views, 583 primary key/foreign key relationships, 524 primary keys use in creating EntityKeys, 148 PrimitiveTypeKind class, 611 PrimitiveTypes, 625 profilers, 73 projections, 78 in Entity SQL, 113 in LINQ to Entities syntax differences in C# and VB, 79 Include method results, with and without projections, 104 in LINQ to Entities, 79–84 projecting into an EntityReference, 85 special language features in C# and VB, 80–84 using LINQ query methods, 84 LINQ nested query as, 91 projecting into EntityReference with Entity SQL, 116 properties from EntityCollections, 87 in queries, 78 query using, filtering related data in, 99 properties accessing for anonymous types, 85 anonymous types as, 83 association, for many-to-many relationship, 737 association, for one-to-many relationship, 734 changing names in new EDM, 170 combining from related entities, 85 complex type, getting from ObjectStateEntry, 615–619 creating custom properties, 286–289 custom, creating for all entities, 294 determining whether property has been modified, 614 entity, 26 entity property defaults versus database and model first, 743 entity property properties, 27 entity, mapping to function input parameters, 147 from EntityCollection entities, projecting, 87 EntityDataSource, setting programmatically, 315 flagging for concurrency checking, 664 names of, collisions with entity names in EDM, 172 naming when grouping in LINQ to Entities, 94 original values stored by self-tracking entities, 508 renaming foreign key properties in EDM, 171 scalar and navigation, 24 self-tracking entity, 504 setting attributes for, 732 types of, 130 viewing information about, 25 Property elements, 37 PropertyChanging and PropertyChanged events, EntityObject, 251, 280 Index | 863 Download from Library of Wow! eBook event parameters, 281 subscribing to class-level events, 281 PropertyChanging and PropertyChanged methods, 271 calculating database columns locally with PropertyChanged, 273 PropertyVirtualModifier method, 496 provider connection string, 244 Provider method, 711 ProviderManifestToken attribute, 44 ProviderName attribute, EntityConnection string, 244 providers available providers for Entity Framework, generation of SQL from command trees, 235 information about, in EntityConnection string, 244 information on, 556 programmatically changing ADO.NET DataProvider, 558 proxies dynamic proxies created at runtime, 496 POCOs using for change notification, lazy loading, and fixing relationships, 345 POCOs using for lazy loading, 346 POCOs using to synchronize relationships, 348 problems created by dynamic proxies, avoiding, 516 proxy classes, 347 rules for getting proxy behavior with POCOs, 349 Q queries adding native queries to the model, 426– 429 avoiding inadvertent execution of, 74 entity, translating to database queries, 71 resources for more sample queries, 109 query builder methods, 64, 235–238 aggregating with, in Entity SQL, 118 combining with LINQ methods, 66, 237 conversion to command tree, 234 conversion to Entity SQL expressions, 237 EntitySets and, 236 projecting with, in Entity SQL, 115 query methods (LINQ), projections with, 84 query operations, WCF service using POCOs, 498 QueryExtender control, 317 querying using EntityClient to return streamed data, 68–71 using LINQ to Entities, 55 using methods, 61 using Object Services and Entity SQL, 57– 60 QueryInterceptor attribute, filtering at service level, 480 QueryView, 388, 411–416 cautions when using, 412 creating mapping for entity encapsulating results, 414 deconstructing, 416 DefiningView versus, 433 entity in model to encapsulate results, 413 entity provided by, in Web Forms application, 797 finding common use case for, 413 providing flattened data for entity in Web Forms, 797 testing, 416 R RAD ASP.NET applications, data binding with, 297–333 building Dynamic Data websites, 329 creating ASP.NET Web Application project, 298 EntityDataSource events, 327 hierarchical data in master/detail form, 317– 327 how EntityDataSource retrieves and accesses data, 304–309 related EntityReference data, 309–317 using EntityDataSource control to access flat data, 298–304 Rapid Application Development (RAD) applications, 297 (see also RAD ASP.NET applications, data binding with) read-only database views, 46 read-only entities, creating using QueryView, 411 864 | Index Download from Library of Wow! eBook RecordOriginalValue method, ChangeTracker, 509 reference properties, client-side object in WCF service, 470 Referential Constraint property, 40 referential constraints automatically created, for association, 735 creating, 382 defining for split table, 382 ReferentialConstraint element in SSDL, 834 reflection combining System.Reflection with MetadataWorkspace, 637–640 instantiating an assembly, 623 ObjectStateManager and MetadataWorkspace versus, 638 Refresh method, 570, 671 refreshing related entities in a graph, 675 using with ClientWins, 671 using with collection of entities, 674 using with StoreWins, 673 RefreshMode, 671 RelatedEnd objects, 621 relationship cardinality, 25 relationship manager and IRelatedEnd interface, 530 getting in code, 531 relationship span, 252, 529 RelationshipEntry, 610 RelationshipEntry objects, 599 RelationshipManager objects, 640 building graphs directly with, 620 RelationshipManager property, ObjectStateEntry, 530, 606 relationships, 521–554 defining between entities, 542 CLR way, setting navigation property to an entity, 543 lazy loading, 545 Load method, 547 loading from detached entities, lazy and explicit, 547 loading, adding, and attaching navigation properties, 545 moving entity to new graph, 550 setting foreign key property, 544 using Attach and Remove methods, 549 using EntityCollection.Add, 548 in the EDM, 522–527 additional relationship items, 525 associations, creation by EDM Wizard, 523 nonessential navigation properties, 526 foreign key versus independent associations, 527 getting foreign key value in independent association, 552 between instantiated entities, 529 deletes and cascading deletes, 540 how Entity Framework manages relationships, 531 late-binding relationships, 530 navigation properties, 534–537 referential integrity and constraints, 537 relationship manager and IRelatedEnd interface, 530 management by ObjectContext, 252–257 management in POCO entities, 537 management of, 13 POCOs’ impact on two-way relationships, 342–345 enabling classes to fix relationships, 344 fixing relationships with DetectChanges method, 343 synchronizing by proxy for POCOs, 348 using CreateSourceQuery to enhance deferred loading, 551 working with, in ObjectStateManager, 620 Remove method, 550 repository classes adding into Web Forms application, 795 building interface they will implement, 702 creating, 703–706 leveraging precompiled queries in, 722 modifying tests to use fake repository, 713 payment repository in ASP.NET MVC application, 817 replacing context with, in ASP.NET MVC application, 813 using in your application, 723 adding UI layer that calls repository, 723 Repository Pattern, 695 REST (Representative State Transfer), 474 RESTful service, WCF Data Services, 484 ReturnType attribute, 407 Index | 865 Download from Library of Wow! eBook RIA (Rich Internet Application) Services (WCF), 449, 485, 490, 520 (see also WCF services) using POCO entities in, 517 rollbacks, 565 changes to entities in context, 570 Rows Affected Parameter Option, 151 RowType element, 407 rowversion fields concurrency checking without, 666 using for concurrency checks, 662 rowversion type, 151, 177 S SaveChanges method, 131–139 affecting default behavior of, 260 ApplyAllChanges versus, 512 catching concurrency exceptions, 676 creating your own System.Transaction for, 566 default transaction within, 565 deleting entities, 137 EDM bound to Windows Forms application, 201 enabling saves in WPF form, 224 exceptions thrown during execution, 654– 657 inserting new parents and children, 135 insetting new objects, 134 integer returned by, 259 moving out of UI in client-side WPF application, 769 overridden, handling concurrency exceptions recursively, 677 overriding, 285 overriding completely, 261 performance comparison for updates, 589 refreshing state of tracked entities, 260 SavingChanges versus, 261 using with newly added derived types, 368 SaveOptions enumeration, 260, 566 DetectAllChanges value, 341 SavingChanges event, 276–280, 276 data validation with, 261 implementing, 277 leveraging ObjectStateManager during, 610 overriding to include validation code, 540 setting default foreign keys without foreign key scalar property, 279 scalar properties, 24 client-side object in WCF service, 470 ConcurrencyMode attribute, 262 defined, 41 ScalarProperty mapping element, 837 setting default values in new EDM, 174 scalar types, mapping functions to, 159 scalar values, representation by DataReaders, 68 ScalarProperty element, Version attribute, 153 schema files, 30 schemas BreakAway database (example), 166 changing database schema name, 746 Conceptual Schema Definition Language (see CDSL) creating database schema, 744 generating database schema from model, 738–744 Store Schema Definition Language (see SSDL) Visual Studio 2010 schema files, 30 scope, variables out of, in LINQ, 96 security, 571–574 guarding against connection piggybacks, 573 guarding against SQL injection, 571 Entity SQL injection, 573 precautions with dynamic queries, 571 mapping functions to entities, 147 SELECT clause, 56 FROM clause preceding SELECT in LINQ, 56 VALUE keyword, 58 SELECT expressions, nested query in place of, in Entity SQL, 119 SELECT statements Entity SQL GROUPBY query returning entities, 121 SELECT VALUE, 125 Selected event, EntityDataSource, 322, 328 SelectedValue, GridView control, 315 SelectedValuePath attribute, 220 Selecting event, EntityDataSource, 328 self-referencing associations, mapping, 400 self-tracking entities, 503–515, 520 classes and extension methods, 513 866 | Index Download from Library of Wow! eBook creating and exploring, 503, 505 creating WCF service that uses, 506 interoperability with, 505 putting change-tracking logic where needed, 505 watching them at work, 507–513 debugging client application, 508 debugging SaveCustomer service method, 511 SequentialAccess behavior, 71 Serializable attribute, 263 serialization, 263–265 automatic, objects as parameters to web or WCF service operations, 264 binary, 265 deserialization of objects attached to ObjectContext, 252 explicit, 265 object state and, 265 objects stored in view state and session state, 792 XML and data contract, 264 server-side tracing and caching provider, 244 session state (ASP.NET), application cache and, 791 SET operators in Entity SQL, 117 SetStoredList and GetStoredList methods, 765 Setter and Getter properties, EDM Designer, 806 SetValue method, 619 SetValues method, 620 shaped results average query times for, 581 projecting properties from EntityCollection entities, 87 returning using expand in WCF data service, 482 shaping data returned by queries, 97–99 with Entity SQL, 122 using Include with ObjectQuery, 123 Include method, 104 limiting related data returned, 99 LINQ query returning shaped results, 97 Silverlight applications, 774 Single method, 75, 107 SingleOrDefault method, 75, 107 SOAP, WCF RIA Services, 485 Solution Explorer, 31 SortDescriptions collection, 225 sorting based on EntityCollections, 88 based on EntityReference property, 86 providing sort capability for UI in WPF client application, 771 split entities (see entity splitting) SQL (Structured Query Language) conversion of queries to, 235 Entity SQL, 58 executing with ExecuteStoreCommand, 440 query executed by Entity Framework after calling Load, 532 SQL injection, guarding against, 74, 571 EntitySQL injection, 573 precautions with dynamic queries, 571 SQL Server, xxxi, 21, 740 data types versus Entity Framework types, 742 rowversion type, 151 timestamp versus rowversion, 177 versions and ProviderManifestToken, 45 versions, use with Entity Framework, SQL Server Modeling CTP Terminology page, 756 SQL Server Modeling, M language, 755–759 SqlClient, SQLClient SqlParameter, 440 SqlClient.SqlTransaction class, 262 SqlDataReader objects, 15 SqlDataSource controls, 14 SqlServer.CHECKSUM function, 667 SSDL (Store Schema Definition Language), 30, 43, 142 adding and deleting entities, 377 additional details of metadata, 833 custom query manually embedded into, 426 defining complex command in, 442 differences from CSDL, 44 functions representing stored procedures, 142 getting functions from, 627 native objects in, 430 user-defined function in, 446 viewing in EDM Designer Model Browser, 155 Index | 867 Download from Library of Wow! eBook startup performance, measuring for queries, 579 state management methods, 793 State property, 493, 517 ObjectStateEntry class, 249, 614 POCO entities in WCF service, 497, 499 self-tracking entities in WCF service, 505, 507, 509 State Server Mode (ASP.NET), 794 StateEntries property, 657, 678 static methods, 290 sticky sessions, 792 storage model, 29 StoreConnection property, 558, 562 stored procedures, 141–163, 419–447 adding native queries to the model, 426– 429 adding native views to model, 429–439 bringing into EDM from database, 142 concurrency checks and, 668 DefiningQuery versus, 434 executing queries on demand with ExecuteStoreQuery, 424 functions created in SSDL to represent, 143 implementing and querying with userdefined functions, 445 mapping first of read stored procedures using imported functions, 158 mapping function to complex type, 160 mapping function to scalar type, 159 mapping functions to entities, 146–155 mapping read stored procedures, 156–159 mapping to entities in new EDM, 175 mapping to split tables, 380 using commands that affect the database, 440–444 working with stored procedures which return data, 420 functions matching entity with changed property names, 421 queries against functions, 423 queries returning multiple result sets, 424 querying stored procedures and inherited types, 422 replacing stored procedures with views, 423 StoreGeneratedPattern attribute, 278 Identity, 741 StoreWins (RefreshMode), 671 using with Refresh method, 673 streaming data EntityClient queries returning streamed data, 68–71 System.ArgumentException, 648 System.Collections.Generic.List, 75 System.Configuration namespace, 559 System.Data namespace, 823 System.Data.Common namespace, 823 System.Data.Entity namespace, 189 System.Data.EntityException, 657 System.Data.Metadata.Edm namespacce, 622 System.Data.Metadata.Edm namespace, 611 System.Data.MetadataException, 648 System.Data.Objects, 51 System.Data.Objects namespace, 231, 751 System.Data.Objects.DataClasses namespace, 405 System.Data.Objects.ObjectResult, 75 System.Data.SqlClient namespace, 50, 823 System.InvalidOperationException, 657 System.Linq namespace, 688 System.Linq.Expressions namespace, 823 System.NotSupportedException, 649 System.Reflection, 637–640 System.Runtime.Serialization namespace, 265 System.Serializable attribute, 263 System.Threading.Tasks namespace, 596 System.Transaction, 564 System.Type, 639 T T-SQL, 740 Entity SQL versus, 58 generated by SqlClient, improvements in, 72 generated to create table (example), 741 query example, T4 (Text Template Transformation Toolkit), 11 T4 (Text Transformation Template Toolkit), 291 (see also templates) T4 (Textual Transformation Template Toolkit) modifying POCO template, 354–358 using to generate POCO classes, 350–354 Table per Hierarchy inheritance (see TPH inheritance) 868 | Index Download from Library of Wow! eBook Table per Type inheritance (see TPT inheritance) table splitting, 381 Tasks class, 596 templated controls, 828 TemplateField controls, 310 templates, 291 customizing for major class modifications, 295 DDL Generation Template, 746 evolving interface and, 699 modifying, 293 POCO classes, directing to model, 492 POCO template, code to inject inheritance into an entity, 494 reading, 292 switching between default and custom templates, 295 switching to, 292 T4 template for generation of DDL, 745 using self-tracking entities template for WCF services, 503–515 test doubles, 694 testing, 685–725 application architecture benefits from testable code, 724 building tests that don't hit database, 714– 722 adding validation logic to context, 716 adding validation logic to POCOs, 714 enabling eager loading in IContext, 721 hiding context from lower layers, 718 precompiled queries in repositories, 722 providing managed entities in fake context, 716 testing unit of work class against database, 720 creating persistent ignorant entities, 694– 714 building interface to represent context, 698 creating fake context, 708 creating interface for repository classes, 702 creating repository classes, 703–706 fake context class, 712 fake ObjectSet class, 710 modifying ObjectContext to implement interface, 699–702 moving POCOs to own project, 695 starting with model and POCO entities, 697 testing method against database, 707 inspecting failed test, 689 writing integration test that hits the database, 687 writing unit test focusing on custom logic, 689–693 Text Template Transformation Toolkit (T4), 11 TextBox controls navigation property, replacing with ComboBoxes, 204 threads forcing ObjectContext to use its own thread, 591 implementing concurrent thread processing, 593 using ObjectContext in multithreaded environments, 591 tiers (application) enabling change tracking across, 766 timestamp type (SQL Server), 177, 662 ToArray method, 75 executing queries with, 241 ToList method, 74 executing queries with, 241 ToTraceString method, ObjectQuery class, 73, 239, 516 TPC (Table per Concrete) inheritance, mapping, 409–411 TPH (Table per Hierarchy) inheritance, 389– 393 code first default to, 755 setting default value on table schema, 391 testing TPH mapping, 392 turning a base class into abstract class, 393 TPT (Table per Type) inheritance, 362–373, 738 with abstract types, 371 default inheritance type for model first, 743 fixing constraint problem, 365 inserting TPT inherited types, 366 mapping, 363 duplicate names and concurrency properties, 363 POCO classes and inherited objects, 366 Index | 869 Download from Library of Wow! eBook querying inherited types, 365 tracing provider, server-side, 244 TrackableCollection, 507 Transact-SQL Editor, 744 transactions, 564–570 handling exceptions for your own transactions, 682 implicit Entity Framework transactions, 565 reasons to use your own, 564 rolling back, 570 specifying your own read-only transactions, 569 specifying your own read/write transactions, 566 support by Object Services, 262 TransactionScope class, 262, 564 TransactionScope objects, 566 TREAT AS operator, 369 TRIM function, 119 try/catch blocks, 645–647 TryGetFunctions method, 627 TryGetItem method, 627 TryGetItems method, 625 TryGetObjectByKey method, 108, 466 TryGetObjectStateEntry method, 603 Type objects, 639 type operators in Entity SQL, 369 TypeOf operator, 369 TypeUsage property, 609, 617 U UDFs (user-defined functions), 419, 445 attributes, 144 in database, representation as functions in EDM, 143 querying with, 446 UI (user interface), 761 (see also persistent ignorant entities, creating) code for WPF layered client application using entities, 770–772 isolating ObjectContext from in layered client application, 762 UI layer that calls repository, 723 Union query method, 628 unit of work adding to Web Forms application, 795 UnitofWork class in ASP.NET MVC application, 813 UnitOfWork objects in Web Forms application, 801 Save method, 802 Unit of Work Pattern, 719 UnitOfWork class (example), 719 testing against database, 720 unit testing, 686 writing test that focuses on custom logic, 689–693 unwrapped results in Entity SQL, 124–127 rules for, 126 Update command, 131 Update function mapping to an entity, 148 mapping to entity concurrency checking, 150 mapping to entity in new EDM, 176 mappings of, Use Original Value checkbox, 176 Update Model from Database feature, 142 Update Model Wizard, 377 Updated event, EntityDataSource, 328 UpdateException, 539 automatic rollback by Entity Framework, 656 gleaning details from, 656 independent association mapping constraints broken, 654 thrown by broken constraints in database, 655 updates affecting with ChangeInterceptor in WCF Data Service, 484 entities in ASP.NET web forms application, 788 fine-tuning for performance, 589 mapping update stored procedure to inherited types, 444 method for, in Web Forms application, 805 retrieving data for, in Web Forms application, 797 update commands in WCF service using POCOs, 502 UpdateCustomer method (example), in WCF service, 464–467 CustomerUpdate object, 473 870 | Index Download from Library of Wow! eBook updating customers by EntityManager class in Web Forms, 801 using rowversion field for concurrency checking, 665 Updating event, EntityDataSource, 328 Use Original Value parameter option, 150 user selection controls in Web Forms, adding lists for, 803 users editing data in Windows Forms, 201 modifying related data in Web Forms application, 805 V validation adding to client-side WPF application form, 769 adding validation logic to context classes, 716 adding validation logic to POCO classes, 714 EDMX schema validation, 831 using GetObjectStateEntries method, 276 Validation Application Block, Microsoft Enterprise Library, 714 VALUE clause (Entity SQL), 59 VALUE keyword, 125 var keyword (C#), 81 variables adding for WPF form, 217 naming ro prevent going out of scope, 96 out of scope, 96 VB (Visual Basic) Aggregate operator for LINQ, 89 anonymous types, 80 generics in, 54 grouping in LINQ to Entities, 93 information on lambdas for developers, 62 LINQ Group BY with explicitly named groups and targets, 95 LINQ query samples, 109 LINQ to Entities query, 55 naming of projected anonymous types, 82 ObjectMaterialized event handler, 275 ObjectSet class declaration, 66 Or operator, 277 projections in, 79 TypeOf operator, 369 vertical splitting (see entity splitting) view generation, 580 view state defined, 789 objects persisted in, page size and, 790 storing small pieces of data in, 790 views, 147, 419 adding native views to model, 429–439 creating your own with DefiningQuery, 431 database views in EDM, 46 MVC applications, Add View Wizard, 808 MVC applications, Edit view, 814 precompiling for performance, 582 pregenerating for performance, 583 pregenerating into existing project, 584 replacing stored procedures with, 423 ViewState EntityDataSource control and, 306 virtual keyword, 346 entities with virtual properties, preventing creation of dynamic properties, 517 marking navigation properties to enable lazy loading, 546 preventing application to properties in POCO template, 496 virtual tables, 430 creating for mapping to DefiningQuery entity, 436 VirtualizingStackPanel element, 220 Visual Studio support for Entity Framework, Visual Studio 2010 DatePicker controls, 219 Extension Manager, 291 POCO Entity Generator, 350 IntelliTrace feature, 73 schema files, 30 Text Template Transformation Toolkit (T4), 11 Visual Studio Gallery page, Database Generation Power Pack, 747 visualizers, building EntityState visualizer using ObjectStateManager, 611–622 W WCF (Windows Communication Foundation) Data Services, 449 RIA Services, 449 Index | 871 Download from Library of Wow! eBook serialization in, 264 WCF services, 15, 449–488, 489–520 building console application to consume EntityObject service, 467–474 enabling client to receive large messages, 468 methods to test service operations, 469– 474 building service using POCO classes, 497– 503 implementing the interface, 498–500 using the service, 500–503 building simple service with EntityObjects, 453–457 creating the service, 453 defining extra service classes, 455 defining service operations, 454 exposing custom properties, 456 creating POCO classes for, 490–497 creating WCF Data Services with entities, 474–485 anticipating exceptions, 481 creating a Data Service, 475–479 exposing related data through service, 481 filtering at service level with QueryInterceptor, 480 limitations of WCF Data Services, 483 modifying data through service, 484 forcing to stay on same port, 467 how WCF RIA Services relate to Entity Framework, 485 implementing service interface, 457 adding graphs to ObjectContext, 460 client rules for identifying changes in EntityCollection, 463 deleting objects, 461 deleting reservations fin UpdateCustomer method, 466 new and existing reservations for UpdateCustomer method, 465 UpdateCustomer method (example), 464 updating object graph, 463 options for creating services, 519 planning Entity Framework-agnostic client, 450 pros and cons of, 451 resources for information on WCF Data Services, 485 using POCO entities with WCF Data and RIA Services, 515 preparing for Data Services, 515 using POCOs in RIA services, 517–519 using self-tracking entities template, 503 change-tracking logic, 505 classes and extension methods of entities, 513 creating self-tracking entities, 503 creating service, 506–513 watching self-tracking entities at work, 507 WCFTestClient utility, 460 web applications (layered), building, 783–819 ASP.NET MVC application, 806–814 editing entities and graphs, 814–818 replacing context with repositories, 813 comparing ASP.NET state solutions to needs of Entity Framework, 789 how ObjectContext fits into web page life cycle, 784 returning results, not queries from DataBridge class, 785 updating entities in ASP.NET web forms application, 788 using EntityObjects in read-only web pages, 786 Web Forms application (layered), building, 793–806 adding lists for user selection controls, 803 allowing user to modify related data, 805 building EntityManager to act as DataBridge, 795 designing the application, 794 getting data from EntityManager to client, 800 making related data accessible to client, 799 retrieving data for display and future updates, 797 using existing repositories, 795 Web Forms applications comparison to MVC, 807 web pages ObjectContext in ASP.NET page life cycle, 784 872 | Index Download from Library of Wow! eBook website for this book, xxxii websites building ASP.NET Dynamic Data websites, 329 WHERE clause, 56, 59, 62 Where clauses type filtering in, 370 WHERE operator, 95 Where property, EntityDataControl, 321 WhereParameters, EntityDataSource, 314, 320, 325 Window.Loaded event, 222 Windows Distributed Transaction Coordinator (DTC), 564 Windows Forms, 187 BackgroundWorker component, 591 creating an application, 188 data binding adding EntityCollection to form, 198 adding new entities, 208–211 allowing users to edit data, 201 binding without a BindingSource, 197 code to query EDM when form loads, 194 displaying properties of related objects in DataGridView, 199 editing navigation properties, 202 getting entity details onto a form, 192 object data source for an entity, 190 user deleting data, 211 using data sources, 189 data sources and complex types, 828 using data sources, 189 Windows Presentation Foundation (see WPF) workflow, 745 WPF (Windows Presentation Foundation), 187–213 BackgroundWorker component, 591 data binding with, 213–230 adding another EntityCollection, 222 adding data source objects, 215 adding items to child EntityCollection, 226 adding new entities, 227 code to query EDM when window loads, 216 creating WPF form, 213 creating WPF project, 214 customizing display of controls, 218 editing entities and related data, 224 inspecting XAML and code from automated data binding, 215 selecting entity and viewing its details, 219 using SortDescriptions, 225 layered client application using entities enabling change tracking across tiers, 766 freeing entities from change tracking, 764–766 isolating ObjectContext, 762 preventing problems from lazy loading, 772 layered client-side application using entities moving logic from ObjectContext to DataBridge, 768–772 wrapped results in Entity SQL, 124–127 rules for, 126 X XAML data-binding elements, 215 selecting entity and viewing its details, 220 XML inspecting mappings in, 152 model-defined function in CSDL section, 404 viewing EDM's raw XML, 31 XML files EDM, database schema, and mapping between, 20 XML serialization, 264 XSD (XML Schema Definition) files, 30 Index | 873 Download from Library of Wow! eBook Download from Library of Wow! eBook About the Author Julia Lerman is the leading independent authority on the Entity Framework and has been using and teaching the technology since its inception in 2006 She is well known in the NET community as a Microsoft MVP, ASPInsider, and INETA Speaker Julie is a frequent presenter at technical conferences around the world and writes articles for many well-known technical publications, including the Data Points column in MSDN Magazine Julie lives in Vermont with her husband, Rich, and gigantic dog, Sampson, where she runs the Vermont.NET User Group You can read her blog at http://thedatafarm.com/ blog/ and follow her on Twitter @julielerman Colophon The animal on the cover of Programming Entity Framework is a Seychelles blue pigeon (Alectroenas pulcherrima) Also known as a Seychelles blue fruit dove, this mediumsize pigeon is approximately 10 inches long and inhabits the woodlands of the Seychelles archipelago Its wings, underbody, and tail are dark blue, while its head and breast are a silvery-gray or a pale blue It has a characteristic patch of crimson skin that runs from its forehead to its crown Its diet consists mostly of fruit The cover image is from Riverside Natural History vol IV The cover font is Adobe ITC Garamond The text font is Linotype Birka; the heading font is Adobe Myriad Condensed; and the code font is LucasFont’s TheSansMonoCondensed Download from Library of Wow! eBook Download from Library of Wow! eBook

Ngày đăng: 04/06/2021, 22:41