C# developers, here's your opportunity to learn the ins-and-outs of Entity Framework Core, Microsoft's recently redesigned object-relational mapper. Benefit from hands-on learning that will teach you how to tackle frustrating database challenges, such as workarounds to missing features in Entity Framework Core, and learn how to optimize the performance of your applications, head-on!
Modern Data Access with Entity Framework Core teaches best practices, guidance, and shortcuts that will significantly reduce the amount of resources you internally dedicate to programming data access code. The proven methods and tools taught in this book, such as how to get better performance, and the ability to select the platform of your choice, will save you valuable time and allow you to create seamless data access. Dive into succinct guidance that covers the gamut-- from installing Entity Framework Core, reverse engineering, forward engineering (including schema migrations), and data reading and modification with LINQ, Dynamic LINQ, SQL, Stored Procedures, and Table Valued Functions- to using third-party products such as LINQPad, Entity Developer, Entity Framework Profiler, EFPlus, and AutoMapper. You'll also appreciate excerpts of conceptual software architecture discussion around Entity Framework Core that might otherwise take years to learn.
What You'll Learn
Understand the core concepts of Entity Framework Core, as well process models for existing databases (reverse engineering) and the generation of database schemas from object models (forward engineering)
Study real-world case studies for hands-on EF Core instruction
Get up to speed with valuable database access scenarios and code samples
Discover workarounds to augment missing features in Entity Framework Core
Use Entity Framework Core to write mobile apps
Bonus online appendix covers Entity Framework Core 2.1 release updates
Who This Book Is For
Software developers who have basic experience with .NET and C#, as well as some understanding of relational databases. Knowledge of predecessor technologies such as ADO.NET and the classic ADO.NET Entity Framework is not necessary to learn from this book.
Author(s): Holger Schwichtenberg
Publisher: Apress
Year: 2018
Language: English
Pages: 644
Table of Contents
About the Author
Introduction
Chapter 1: Introducing Entity Framework Core
What Is an Object-Relational Mapper?
OR Mappers in the .NET World
Version History of Entity Framework Core
Supported Operating Systems
Supported .NET Versions
Supported Visual Studio Versions
Supported Databases
Features of Entity Framework Core
Functions That Have Been Eliminated
Missing Critical Features
High-Priority Features
New Features in Entity Framework Core
When to Use Entity Framework Core
Chapter 2: Installing Entity Framework Core
NuGet Packages
Installing the Packages
Updating to a New Version
Chapter 3: Concepts of Entity Framework Core
Process Models for Entity Framework Core
Components of Entity Framework Core
Chapter 4: Reverse Engineering of Existing Databases (Database First Development)
Using Reverse Engineering Tools
Reverse Engineering with PowerShell Cmdlets
Generating Code
Looking at the Generated Program Code
Seeing an Example Client
Using the .NET Core Tool dotnet
Understanding the Weaknesses of Reverse Engineering
Chapter 5: Forward Engineering for New Databases
Two Types of Classes
Examples in This Chapter
Rules for Self-Created Entity Classes
NuGet Packages
Data Annotation Properties
Data Types
Relationships (Master-Detail)
Inheritance
Primary Key
Examples
Rules for the Self-Created Context Class
Installing the NuGet Packages
Base Class
Constructor
References to Entity Classes
Provider and Connection String
Seeing an Example
Your Own Connections
Thread Safety
Rules for Database Schema Generation
Looking at an Example Client
Adaptation by Fluent API (OnModelCreating())
Viewing the Generated Database Schema
Chapter 6: Customizing the Database Schema
Examples in This Chapter
Convention vs. Configuration
Persistent vs. Transient Classes
Names in the Database Schema
Order of Columns in a Table
Column Types/Data Types
Mandatory Fields and Optional Fields
Field Lengths
Primary Keys
Relationships and Foreign Keys
Optional Relationships and Mandatory Relationships
Unidirectional and Bidirectional Relationships
1:1 Relationships
Indexes
Syntax Options for the Fluent API
Sequential Configuration
Structuring by Lambda Statement
Structuring by Subroutines
Structuring Through Configuration Classes
Bulk Configuration with the Fluent API
Chapter 7: Database Schema Migrations
Creating the Database at Runtime
Schema Migrations at the Time of Development
Commands for the Schema Migrations
ef.exe
Add-Migration
Update-Database
Script-Migration
Further Migration Steps
Migration Scenarios
More Options
Problems with Schema Migration in Connection with TFS
Schema Migrations at Runtime
Chapter 8: Reading Data with LINQ
Context Class
LINQ Queries
Step-by-Step Composition of LINQ Queries
Use of var
Repository Pattern
LINQ Queries with Paging
Projections
Projection to an Entity Type
Projections to an Anonymous Type
Projections to an Arbitrary Type
Querying for Single Objects
Loading Using the Primary Key with Find()
Using LINQ in RAM Instead of in the Database (Client Evaluation)
Using the Wrong Order of Commands
Using Custom Function in LINQ
Working Around the GroupBy Problem
Mapping to Nonentity Types
Creating an Entity Class for the Database View Result
Including the Entity Class in the Context Class
Using the Pseudo-Entity Class
Challenge: Migrations
Groupings with Database Views
Brief Overview of the LINQ Syntax
Simple SELECT Commands (All Records)
Conditions (where)
Contains (in)
Sorts (orderby)
Paging (Skip() and Take())
Projection
Aggregate Functions (Count(), Min(), Max(), Average(), Sum())
Groupings (GroupBy)
Single Objects (SingleOrDefault(), FirstOrDefault())
Related Objects (Include())
Inner Join
Cross Join (Cartesian Product)
Join with a Grouping
Subqueries (Subselects)
Chapter 9: Object Relationships and Loading Strategies
Overview of Loading Strategies
Seeing the Default Behavior
No Lazy Loading Yet
Explicit Loading
Eager Loading
Relationship Fixup
Example for Case 1
Example for Case 2
Example for Case 3
Preloading with Relationship Fixup
Chapter 10: Inserting, Deleting, and Modifying Records
Saving with SaveChanges()
Tracking Changes for Subobjects
Combining Commands (Batching)
Dealing with foreach Loop Considerations
Adding New Objects
Creating Related Objects
Changing Linked Objects
Dealing with Contradictory Relationships
Deleting Objects
Deleting Objects with Remove()
Deleting Objects with a Dummy Object
Bulk Deleting
Performing Database Transactions
Example 1
Example 2
Using the Change Tracker
Getting the State of an Object
Listing All Changed Objects
Chapter 11: Preventing Conflicts (Concurrency)
A Look at the History of Concurrency
No Conflict Detection by Default
Detecting Conflicts with Optimistic Locking
Detecting Conflicts for All Properties
Settling Conflicts by Convention
Setting Up Conflict Checks Individually
Adding Timestamps
Resolving Conflicts
Pessimistic Locking on Entity Framework Core
Chapter 12: Logging
Using the Extension Method Log()
Implementing the Log() Extension Method
Logging Categories
Chapter 13: Asynchronous Programming
Asynchronous Extension Methods
ToListAsync()
SaveChangesAsync()
ForEachAsync()
Chapter 14: Dynamic LINQ Queries
Creating LINQ Queries Step-by-Step
Expression Trees
Using Dynamic LINQ
Chapter 15: Reading and Modifying Data with SQL, Stored Procedures, and Table-Valued Functions
Writing Queries with FromSql()
Using LINQ and SQL Together
Using Stored Procedures and Table-Valued Functions
Using Nonentity Classes as Result Sets
Using SQL DML Commands Without Result Sets
Chapter 16: Tips and Tricks for Mapping
Shadow Properties
Automatic Shadow Properties
Defining a Shadow Property
Getting the Output of All Shadow Properties of an Entity Class
Reading and Changing a Shadow Property
Writing LINQ Queries with Shadow Properties
Practical Example: Automatically Updating the Shadow Property Every Time You Save
Computed Columns
Automatic SELECT
Practical Example: Creating Columns with a Calculation Formula
Using Columns with a Calculation Formula
Using Columns with a Calculation Formula in Reverse Engineering
Default Values
Defining Default Values for Forward Engineering
Using Default Values
Practical Example: Defaults Already Assigned When Creating the Object
Using Default Values for Reverse Engineering
Table Splitting
Sequence Objects (Sequences)
What Are Sequences?
Creating Sequences at Forward Engineering
Seeing Sequences in Action
Alternative Keys
Defining Alternative Keys
Seeing Alternative Keys in Use
Cascading Delete
Delete Options in Entity Framework Core
Looking at an Example
Mapping of Database Views
Creating a Database View
Creating an Entity Class for the Database View
Including the Entity Class in the Context Class
Using the Database View
Challenge: Migrations
Global Query Filters
Defining a Filter
Using Filters in LINQ
Practical Example: Ignoring a Filter
Global Query Filters for SQL Queries
Global Query Filters for Stored Procedures and Table-Valued Functions
Future Queries
Chapter 17: Performance Tuning
Process Model for Performance Optimization in Entity Framework Core
Best Practices for Your Own Performance Tests
Performance Comparison of Various Data Access Techniques in .NET
Optimizing Object Assignment
Bulk Operations
Single Delete
Optimization with Batching
Delete Without Loading with Pseudo-Objects
Using Classic SQL Instead of the Entity Framework Core API
Lambda Expressions for Mass Deletion with EFPlus
Bulk Update with EFPlus
Performance Optimization Through No-Tracking
Activating No-Tracking Mode
No-Tracking Mode Is Almost Always Possible
No-Tracking Mode in an Editable Data Grid
QueryTrackingBehavior and AsTracking()
Consequences of No-Tracking Mode
Best Practices
Selecting the Best Loading Strategy
Caching
MemoryCache
CacheManager
Second-Level Caching with EFPlus
Setting Up a Second-Level Cache
Using the Second-Level Cache
Chapter 18: Software Architecture with Entity Framework Core
Monolithic Model
Entity Framework Core as a Data Access Layer
Pure Business Logic
Business Classes and ViewModel Classes
Distributed Systems
Conclusion
Chapter 19: Commercial Tools
Entity Framework Core Power Tools
Features
Reverse Engineering with Entity Framework Core Power Tools
Charts with Entity Framework Core Power Tools
LINQPad
Using LINQPad
Including Data Sources
Executing LINQ Commands
Saving
Other LINQPad Drivers
Interactive Program Code Entry
Conclusion to LINQPad
Entity Developer
Selecting the ORM Technique
Reverse Engineering with Entity Developer
Forward Engineering with Entity Developer
Entity Framework Profiler
Integrating Entity Framework Profiler
Monitoring Commands with the Entity Framework Profiler
Alerts and Suggestions
Analysis
Command-Line Support and API
Conclusion to Entity Framework Profiler
Chapter 20: Additional Components
Oracle Database Driver by DevArt
Installation
Tools
Context Class
Entity Classes
Data Types
Entity Framework Plus
Second-Level Caching with EFSecondLevelCache.Core
Object-Object Mapping with AutoMapper
Object-to-Object Mapping via Reflection
AutoMapper
Looking at an Example
Configuring Mappings
Running the Mapping with Map()
Using the Nonstatic API
Mapping Conventions
Changing Mapping Conventions
Profile Classes
Ignoring Subobjects
Custom Mappings
Type Conversions
Collections
Inheritance
Generic Classes
Additional Actions Before and After the Mapping
Performance
Conclusion to AutoMapper
Appendix A: Case Studies
Using Entity Framework Core in an ASP.NET Core Application
Architecture
Entity
Entity Framework Core Context Class
Lifetime of Context Class in ASP.NET Core Applications
Business Logic
Web API
Using Entity Framework Core via Dependency Injection
Practical Example: Context Instance Pooling (DbContext Pooling)
Using Entity Framework Core in a Universal Windows Platform App
Architecture
Entity
Entity Framework Core Context Class
Start Code
Generated Database
Data Access Code
User Interface
Using Entity Framework Core in a Xamarin Cross-Platform App
Architecture
Entity
Entity Framework Core Context Class
Start Code
Generated Database
Data Access Code
User Interface
Many-to-Many Relationship to Oneself
Appendix B: Internet Resources
Appendix C: New Features in Entity Framework Core 2.1
Index