Table Of ContentSECOND EDITION
Jon P Smith
Foreword by Julie Lerman
M A N N I N G
The following table provides a list of topics covered in this book, with a list of chapters
where that topic is covered, with the primary chapter at the front. It also lists any key
figures that go with this topic.
Topics Chapters Key figures (chapter.figure)
Setting up EF Core 1, 2, 7, 8, 5 1.4, 2.7, 1.5
Query the database 2, 5, 6 2.7, 2.8, 6.2
Create, Update, Delete 3, 5, 8, 11 3.1, 3.2, 6.8 to 10
How EF Core works inside 1, 6 1.6, 1.8, 1.10, 6.8 to 6.10
Business Logic 4, 5, 13 4.2, 4.4, 5.4
ASP.NET Core 5, 2 5.1, 5.4
Dependency injection 5, 14, 15 5.2, 5.3
Async/await 5, 14 5.8, 5.9
Configure non-relational 7 7.1, 7.2
Configure relationships 8 8.1, 8.2, 8.3, 8.4
Configure table mappings 8 8.12, 8.13
Database migrations 9, 5 9.2, 9.3, 9.5, 9.7, 9.8
Concurrency issues 10, 15 10.3, 10.4, 10.5, 10.6, 10.7, 15.7
Using raw SQL 11, 6 15.3
Domain-Driven design 13, 4 13.3, 4.2, 13.4, 13.5
Performance tuning 14, 15, 16 14.1, 15.2, 15.4, 15.9, 16.7, 16.8
Cosmos DB & other databases 16, 17 16.1, 16.3, 16.4, 17.5
Data Validation 4, 7, 10
Unit testing 17 17.2, 17.3
LINQ language Appendix, 2 A.2, A.1
context.Books.Where(p => p.Title.StartsWith("Quantum").ToList();
Application’s DbContext A series of LINQ and/or An execute
property access EF Core commands command
An example of an Entity Framework Core database query
Praise for the first edition
This book helped highlight some issues my team was having with EF Core and has become an invaluable
resource that takes pride of place on our bookshelves.
—Evan Wallace, senior software Developer at Berkley Insurance Australia
The most complete go-to book for anything you need to know about EF Core! The #1 must-have EF Core
reference for your library!
—Mauro Quercioli, senior independent software architect/developer, Siena I.T. Consulting Corporation
Knowing that EF Core in Action is right there on my desk, I am approaching my latest assignment—to
build out a new WebAPI application using Entity Framework Core—with complete confidence. The book
addresses everything we needed to know about EF Core and more!
—Phil Taffet, senior .NET developer, California Earthquake Authority
Finally a book to learn all about EF Core. It’s fun and engaging reading this. Be careful—whether you’re a
beginner or professional, you’ll learn something.
—Raushan Kumar Jha, SE-2, Microsoft India (R&D)
This is a solid book dealing well with the topic in hand but also handling the wider concerns around using
Entity Framework in real-world applications.
—Sebastian Rogers, technical director, Simple Innovations
Entity Framework
Core in Action
SECOND EDITION
JON P SMITH
FOREWORD BY JULIE LERMAN
MANNING
SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: [email protected]
©2021 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning Publications
was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books
are printed on paper that is at least 15 percent recycled and processed without the use of
elemental chlorine.
Development editor: Marina Michaels
Technical development editor: Joel Kotarski
Manning Publications Co. Review editor: Aleksandar Dragosavljevic´
20 Baldwin Road Production editor: Keri Hales
PO Box 761 Copy editor: Keir Simpson
Shelter Island, NY 11964 Proofreader: Melody Dolab
Technical proofreader: Julien Pohie
Typesetter: Dennis Dalinnik
Cover designer: Marija Tudor
ISBN: 9781617298363
Printed in the United States of America
contents
foreword xxi
preface xxiii
acknowledgments xxv
about this book xxvii
about the author xxxii
about the cover illustration xxxiii
PART 1 ........................................................................ 1
1 Introduction to Entity Framework Core 3
1.1 What you’ll learn from this book 4
1.2 My “lightbulb moment” with Entity Framework 5
1.3 Some words for existing EF6.x developers 6
1.4 An overview of EF Core 7
The downsides of O/RMs 7
1.5 What about NoSQL? 8
1.6 Your first EF Core application 9
What you need to install 9 ■ Creating your own .NET Core console
app with EF Core 10
1.7 The database that MyFirstEfCoreApp will access 11
v
vi CONTENTS
1.8 Setting up the MyFirstEfCoreApp application 13
The classes that map to the database: Book and Author 13
The application’s DbContext 14
1.9 Looking under the hood of EF Core 15
Modeling the database 15 ■ Reading data from the database 17
Updating the database 20
1.10 The stages of development of EF Core 23
1.11 Should you use EF Core in your next project? 24
.NET is the future software platform, and it’s fast! 24 ■ Open
source and open communication 24 ■ Multiplatform applications
and development 24 ■ Rapid development and good features 25
Well supported 25 ■ Always high-performance 25
1.12 When should you not use EF Core? 26
2 Querying the database 27
2.1 Setting the scene: Our book-selling site 28
The Book App’s relational database 28 ■ Other relationship types
not covered in this chapter 31 ■ The database showing all the
tables 32 ■ The classes that EF Core maps to the database 33
2.2 Creating the application’s DbContext 35
Defining the application’s DbContext: EfCoreContext 35
Creating an instance of the application’s DbContext 35
Creating a database for your own application 37
2.3 Understanding database queries 38
Application’s DbContext property access 39 ■ A series of LINQ/EF
Core commands 39 ■ The execute command 39 ■ The two types
of database queries 40
2.4 Loading related data 40
Eager loading: Loading relationships with the primary entity
class 40 ■ Explicit loading: Loading relationships after the
primary entity class 43 ■ Select loading: Loading specific parts of
primary entity class and any relationships 44 ■ Lazy loading:
Loading relationships as required 45
2.5 Using client vs. server evaluation: Adapting data
at the last stage of a query 47
2.6 Building complex queries 49
2.7 Introducing the architecture of the Book App 52
CONTENTS vii
2.8 Adding sorting, filtering, and paging 54
Sorting books by price, publication date, and customer ratings 54
Filtering books by publication year, categories, and customer
ratings 55 ■ Other filtering options: Searching text for a specific
string 56 ■ Paging the books in the list 58
2.9 Putting it all together: Combining Query Objects 58
3 Changing the database content 61
3.1 Introducing EF Core’s entity State 62
3.2 Creating new rows in a table 62
Creating a single entity on its own 63 ■ Creating a book
with a review 64
3.3 Updating database rows 67
Handling disconnected updates in a web application 69
3.4 Handling relationships in updates 74
Principal and dependent relationships 75 ■ Updating one-to-one
relationships: Adding a PriceOffer to a book 76 ■ Updating one-to-
many relationships: Adding a review to a book 80 ■ Updating a
many-to-many relationship 83 ■ Advanced feature: Updating
relationships via foreign keys 87
3.5 Deleting entities 88
Soft-delete approach: Using a global query filter to hide entities 88
Deleting a dependent-only entity with no relationships 90
Deleting a principal entity that has relationships 90 ■ Deleting
a book with its dependent relationships 91
4 Using EF Core in business logic 94
4.1 The questions to ask and the decisions you need to make
before you start coding 95
The three levels of complexity of your business logic code 95
4.2 Complex business logic example: Processing an order
for books 97
4.3 Using a design pattern toimplement complex business
logic 98
Five guidelines for building business logic that uses EF Core 98
4.4 Implementing the businesslogic for processing an
order 99
Guideline 1: Business logic has first call on defining the database
structure 100 ■ Guideline 2: Business logic should have no
viii CONTENTS
distractions 101 ■ Guideline 3: Business logic should think that
it’s working on in-memory data 102 ■ Guideline 4: Isolate the
database access code into a separate project 105 ■ Guideline 5:
Business logic shouldn’t call EF Core’sSaveChanges 106 ■ Putting
it all together: Calling the order-processing business logic 108
Placing an order in the Book App 109 ■ The pros and cons of the
complex business logic pattern 111
4.5 Simple business logic example: ChangePriceOfferService 111
My design approach for simple business logic 112 ■ Writing the
ChangePriceOfferService code 112 ■ The pros and cons of this
business logic pattern 113
4.6 Validation business logic example: Adding review to a
book, with checks 113
The pros and cons of this business logic pattern 114
4.7 Adding extra features to your business logic handling 115
Validating the data that you write to the database 115 ■ Using
transactions to daisy-chain a sequence of business logic code 119
Using the RunnerTransact2WriteDb class 122
5 Using EF Core in ASP.NET Core web applications 125
5.1 Introducing ASP.NET Core 126
5.2 Understanding the architecture of the Book App 126
5.3 Understanding dependency injection 127
Why you need to learn about DI in ASP.NET Core 128 ■ A basic
example of dependency injection in ASP.NET Core 128 ■ The
lifetime of a service created by DI 129 ■ Special considerations
for Blazor Server applications 131
5.4 Making the application’s DbContext available via DI 131
Providing information on the database’s location 131
Registering your application’s DbContext with the DI provider 132
Registering a DbContext Factory with the DI provider 134
5.5 Calling your database access code from ASP.NET Core 134
A summary of how ASP.NET Core MVC works and the terms it
uses 135 ■ Where does the EF Core code live in the Book App? 135
5.6 Implementing the book list query page 136
Injecting an instance of the application’s DbContext via DI 137
Using the DbContext Factory to create an instance of a
DbContext 138