Programming Entity Framework: DbContext

Book description

The DbContext API captures Entity Framework’s (EF) most commonly used features and tasks, simplifying development with EF. This concise book shows you how to use the API to perform set operations with the DbSet class, handle change tracking and resolve concurrency conflicts with the Change Tracker API, and validate changes to your data with the Validation API.

With DbContext, you’ll be able to query and update data, whether you’re working with individual objects or graphs of objects and their related data. You’ll find numerous C# code samples to help you get started. All you need is experience with Visual Studio and database management basics.

  • Use EF’s query capabilities to retrieve data, and use LINQ to sort and filter data
  • Learn how to add new data, and change and delete existing data
  • Use the Change Tracker API to access information EF keeps about the state of entity instances
  • Control change tracking information of entities in disconnected scenarios, including NTier applications
  • Validate data changes before they’re sent to the database, and set up validation rules
  • Bypass EF’s query pipeline and interact directly with the database

Publisher resources

View/Submit Errata

Table of contents

  1. Preface
    1. Audience
    2. Contents of This Book
    3. Conventions Used in This Book
    4. Using Code Examples
    5. Safari® Books Online
    6. How to Contact Us
    7. Acknowledgments
  2. 1. Introducing the DbContext API
    1. Getting the DbContext API into Your Project
    2. Looking at Some Highlights of the DbContext API
      1. Reducing and Simplifying Ways to Work with a Set
      2. Retrieving an Entity Using ID with DbSet.Find
      3. Avoiding Trolling Around the Guts of Entity Framework
    3. Working with the BreakAway Model
      1. Getting the Sample Solution
      2. Getting DbContext from an EDMX Model
    4. Ensuring DbContext Instances Get Disposed
  3. 2. Querying with DbContext
    1. Writing Queries with LINQ to Entities
    2. Querying All the Data from a Set
    3. Using LINQ for Sorting, Filtering, and More
    4. Finding a Single Object
    5. Querying Local Data
      1. Using the Load Method to Bring Data into Memory
      2. Running LINQ Queries Against Local
      3. Working with the ObservableCollection Returned by Local
    6. Loading Related Data
      1. Lazy Loading
        1. Understanding the downsides of lazy loading
      2. Eager Loading
        1. Understanding the downsides of eager loading
        2. Using Include in LINQ queries
      3. Explicit Loading
      4. Checking If a Navigation Property Has Been Loaded
    7. Querying Contents of a Collection Navigation Property
      1. Explicit Loading a Subset of the Contents of a Navigation Property
  4. 3. Adding, Changing, and Deleting Entities
    1. Working with Single Entities
      1. Adding New Entities
      2. Changing Existing Entities
      3. Deleting Existing Entities
        1. Deleting without loading from the database
        2. Deleting an object with related data
      4. Multiple Changes at Once
      5. The “Find or Add” Pattern
    2. Working with Relationships
      1. Adding a Relationship Between Objects
      2. Changing a Relationship Between Objects
      3. Removing a Relationship Between Objects
    3. Working with Change Tracking
    4. Using Snapshot Change Tracking
      1. Understanding When Automatic Change Detection Occurs
      2. Controlling When DetectChanges Is Called
      3. Using DetectChanges to Trigger Relationship Fix-up
    5. Enabling and Working with Change Tracking Proxies
      1. Ensuring the New Instances Get Proxies
      2. Creating Proxy Instances for Derived Types
    6. Fetching Entities Without Change Tracking
  5. 4. Working with Disconnected Entities Including N-Tier Applications
    1. A Simple Operation on a Disconnected Graph
    2. Exploring the Challenges of N-Tier
      1. Using Existing N-Tier Frameworks That Support Graph Modification
      2. Using Explicit Operations on the Server Side
      3. Replaying Changes on the Server
    3. Understanding How DbContext Responds to Setting the State of a Single Entity
      1. Marking a New Entity as Added
      2. Marking an Existing Entity as Unchanged
      3. Marking an Existing Entity as Modified
      4. Registering an Existing Entity for Deletion
        1. Using a stub entity to mark for deletion
      5. Working with Relationships with and Without Foreign Keys
        1. Benefiting from foreign key properties
        2. Using navigation properties to define relationships
    4. Setting the State for Multiple Entities in an Entity Graph
      1. Getting the Graph into the Context
      2. Setting the State of Entities in a Graph
    5. Building a Generic Approach to Track State Locally
      1. Creating a Generic Method That Can Apply State Through Any Graph
      2. Concurrency Implications
    6. Tracking Individually Modified Properties
      1. Recording Modified Property Names
        1. Concurrency implications
      2. Recording Original Values
        1. Concurrency implications
      3. Querying and Applying Changes
        1. Concurrency implications
  6. 5. Change Tracker API
    1. Change Tracking Information and Operations for a Single Entity
    2. Working with the State Property
    3. Working with Current, Original, and Database Values
      1. Working with DbPropertyValues for Complex Types
      2. Copying the Values from DbPropertyValues into an Entity
      3. Changing Values in a DbPropertyValues
        1. Using the SetValues method
    4. Working with Individual Properties
      1. Working with Scalar Properties
      2. Working with Complex Properties
      3. Working with Navigation Properties
        1. Modifying the value of a navigation property
        2. Modifying navigation properties with the change tracker
        3. Working with collection navigation properties
    5. Refreshing an Entity from the Database
    6. Change Tracking Information and Operations for Multiple Entities
    7. Using the Change Tracker API in Application Scenarios
      1. Resolving Concurrency Conflicts
      2. Logging During Save Changes
  7. 6. Validating with the Validation API
    1. Defining and Triggering Validation: An Overview
    2. Validating a Single Object on Demand with GetValidationResult
    3. Specifying Property Rules with ValidationAttribute Data Annotations
      1. Validating Facets Configured with the Fluent API
      2. Validating Unmapped or “Transient” Properties
      3. Validating Complex Types
      4. Using Data Annotations with an EDMX Model
    4. Inspecting Validation Result Details
      1. Inspecting Individual Validation Errors
    5. Exploring More ValidationAttributes
      1. Using CustomValidationAttributes
    6. Validating Individual Properties on Demand
    7. Specifying Type-Level Validation Rules
      1. Using IValidatableObject for Type Validation
      2. Validating Multiple Rules in IValidatableObject
      3. Using CustomValidationAttributes for Type Validation
    8. Understanding How EF Combines Validations
    9. Validating Multiple Objects
    10. Validating When Saving Changes
      1. Reviewing ObjectContext. SaveChanges Workflow
      2. Understanding DbContext.SaveChanges Workflow
      3. Disabling Validate Before Save
  8. 7. Customizing Validations
    1. Overriding ValidateEntity in the DbContext
    2. Considering Different Ways to Leverage ValidateEntity
    3. Updating Data During SaveChanges
    4. Overriding SaveChanges When Validation Occurs
      1. Comparing ValidateEntity to SaveChanges for Custom Logic
    5. Using the IDictionary Parameter of ValidateEntity
    6. Controlling Which Entities Are Validated in ValidateEntity
  9. 8. Using DbContext in Advanced Scenarios
    1. Moving Between ObjectContext and DbContext
      1. Accessing ObjectContext Features from a DbContext
      2. Adding DbContext into Existing .NET 4 Applications
    2. Leveraging SQL Server Operators Exposed in SqlFunctions
    3. Querying Derived Types with DbSet
    4. Understanding the Interface Property Limitation
    5. Considering Automated Testing with DbContext
      1. Testing with DbSet
      2. Exploring a Scenario That Unnecessarily Queries the Database
    6. Reducing Database Hits in Testing with IDbSet
      1. Creating an IDbSet Implementation
      2. Abstracting BreakAwayContext for Tests
      3. Reviewing the Implementation
      4. Supplying Data to a FakeDbSet
    7. Accessing the Database Directly from DbContext
      1. Executing Queries with Database.SqlQuery and DbSet.SqlQuery
      2. Tracking Results of SqlQuery
      3. Executing Commands from the Database Class
    8. Providing Multiple Targeted Contexts in Your Application
      1. Reusing Classes, Configurations, and Validation Across Multiple Contexts
      2. Ensuring That All DbContexts Use a Single Database
      3. Validating Relationship Constraints and Other Validations with Multiple Contexts
      4. Getting Code First to Create Full BreakAwayContext Database
  10. 9. What’s Coming Next for Entity Framework
    1. Understanding Entity Framework’s Version Numbers
    2. Entity Framework 5.0
      1. Enums
      2. Spatial Data
      3. Performance Improvements
      4. Multiple Result Sets from Stored Procedures
      5. Table Value Functions
  11. About the Authors
  12. Copyright

Product information

  • Title: Programming Entity Framework: DbContext
  • Author(s): Julia Lerman, Rowan Miller
  • Release date: February 2012
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449312961