Entity Framework Core in Action
Jon P Smith
  • MEAP began February 2017
  • Publication in April 2018 (estimated)
  • ISBN 9781617294563
  • 470 pages (estimated)
  • printed in black & white

Reading and storing data is a core part of any application, and as a .NET developer you want database access to be easy and intuitive. Entity Framework Core is a .NET library designed to simplify data persistence, bridging the mismatch between the different structures of object-oriented code and relational databases. With EF Core, you can access data using abstract objects and properties without tightly coupling your code to the underlying relational database structure. And because it's part of Microsoft's open source .NET Core initiative, EF works on Windows, Linux and MacOS, and even mobile platforms via Microsoft's Xamarin.

"This book is a must have to start your journey with EF Core framework."

~ Julien Pohie

"The author is clearly a total expert."

~ Stephen Byrne

"Coherent, concise and to the point, the material is well written and it's a pleasure to read it."

~ Philip Taffet

Table of Contents detailed table of contents

Part 1: Getting started

1. Introduction to Entity Framework Core

1.1. What you will learn from this book

1.2. My "lightbulb moment" with EF

1.3. Some words for existing EF6.x developers

1.4. An overview of what EF Core is

1.4.1. The down sides of O/RMs

1.5. What about NoSQL?

1.6. My First EF Core application

1.6.1. What you will need to install

1.6.2. Creating your own .NET Core console application with EF Core

1.7. The database my MyFirstEfCoreApp application will access

1.8. Setting up the MyFirstEfCoreApp application

1.8.1. The classes that map to the database — Book and Author classes

1.8.2. The application's DbContext

1.9. Looking "under the hood" of EF Core

1.9.1. Modelling the database

1.9.2. Reading data from the database

1.9.3. Updating the database

1.10. Should I use EF Core in my next project?

1.10.1. Latest generation

1.10.2. Multi-platform and open-source

1.10.3. Rapid development

1.10.4. Well supported

1.10.5. Access to NuGet libraries

1.10.7. Stable Library

1.10.8. Always high performance

1.11. When should you not use EF Core

1.12. Summary

2. Querying the database

2.1. Setting the scene — my book selling site example

2.1.1. The book app’s relational database

2.1.2. Other relationship types not covered in this chapter

2.1.3. The final database showing all the tables

2.1.4. The classes that EF Core maps to the database

2.2. Creating the application’s DbContext

2.2.1. Defining my application’s DbContext: EfCoreContext

2.2.2. Creating an instance of my application’s DbContext

2.2.3. Creating a database for your own application

2.3. Anatomy of a database query

2.3.1. Application’s DbContext Property access

2.3.2. A series of LINQ/EF Core command

2.3.3. The execute command

2.4.1. Eager loading: loading relationships with the primary entity class

2.4.2. Explicit loading: loading relationships after the primary entity class

2.4.3. Select loading: loading the specific parts of primary entity class and any relationships

2.5. Client vs. Server evaluation: moving part of your query into software

2.5.1. An example of using Client vs. Server evaluation to create the display string of s book’s authors

2.5.2. Understanding the limitations of Client vs. Server evaluation

2.6. Building complex queries – the book list display

2.6.1. Building the book list query using select loading

2.6.2. Introducing the architecture of the book app

2.7. Adding Sorting, Filtering, and Paging to the book app

2.7.1. The sorting of books by price, publication date and customer ratings

2.7.2. The filtering of books by publication year and customer ratings

2.7.3. The paging of the books in the list

2.8. Putting it all together: how to combine query objects

2.9. Summary

3. Changing the database content

3.1. Introducing EF Core's entity State

3.2. Creating new entries

3.2.1. Create a single entity on its own

3.2.2. Creating a book with a Review

3.3. The core commands for updating database entries

3.3.1. Handling updates in web application - the disconnected update

3.4. Handling relationships in updates

3.4.1. Principal and dependent relationships

3.4.2. Updating One-to-One relationships – adding a PriceOffer to a book

3.4.3. Updating One-to-Many relationships – adding a review to a book

3.4.4. Updating Many-to-Many relationships – changing a book’s authors

3.4.5. Advanced feature – Updating relationships via foreign key

3.5. Deleting entities

3.5.1. Soft delete - using model-level query filters to ‘hide’ entities

3.5.2. Deleting a dependent-only entity – no relationships

3.5.3. Deleting a principal entity which has relationships

3.6. Summary

4. Using EF Core in business logic

4.1. Why is business logic so different to other code you write?

4.2. My business need – processing an order for books

4.2.1. The business rules that I need to implement

4.3. A design pattern to help you implement business logic

4.3.1. Five guidelines for building business logic that uses EF Core

4.4. Implementing the processing an order business logic

4.4.1. Guideline 1: The business logic has first call on how the database structure is defined

4.4.2. Guideline 2: The business logic should have no distractions

4.4.3. Guideline 3: Business logic should think it is working on in-memory data

4.4.4. Guideline 4: Isolate the database access code into a separate project

4.4.5. Guideline 5: The business logic should not call EF Core’s SaveChanges

4.4.6. Putting it all together – calling the order processing business logic

4.4.7. Any disadvantages of this business logic pattern?

4.5. Placing an order on the book app

4.6. Adding extra feature to our business logic handling

4.6.1. Validating the data that you write to the database

4.6.2. Using transactions to daisy-chain a sequence of business logic code

4.7. Summary

5. Using EF Core in ASP.NET Core web applications

5.1. Introduction to ASP.NET Core

5.2. The architecture of the book app

5.3. Understanding dependency injection (DI)

5.3.1. Why you need learn about dependency injection in ASP.NET Core

5.3.2. A basic example of dependency injection in ASP.NET Core

5.3.3. The lifetime of a service created by DI

5.4. Making the application’s DbContext available via DI

5.4.1. Providing information on where the database is located

5.4.2. Registering your application’s DbContext with the DI provider

5.5. Calling your database access code from ASP.NET Core

5.5.1. A summary of how ASP.NET Core works and the terms it uses

5.5.2. Where does the EF Core code live in the book app?

5.6. Implementing the book list query page

5.7. Implementing my database methods as a DI service

5.7.1. Registering my class as a DI service

5.7.2. Inject the ChangePubDateService into the ASP.NET action method

5.7.3. Improving registering your database access classes as services

5.8. Deploying an ASP.NET Core application with a database

5.8.1. How EF Core knows where the database is on the web server

5.8.2. Creating and migrating the database

5.9. Using EF Core’s Migrate to change the database structure

5.9.1. How do I update my production database?

5.9.2. Having your application migrate your database on startup

5.10. Using async/await for better scalability

5.10.1. Why async/await is useful in a web application using EF Core

5.10.2. Where should I use async/await with database accesses?

5.10.3. Changing over to using async/await versions of EF Core commands

5.11. Running parallel tasks: how to provide the DbContext

5.11.1. Other ways of obtaining a new instance of the application’s DbContext

5.12. Summary

Part 2: Entity Framework in depth

6. Configuring non-relational properties

6.1. The three ways to configure EF Core

6.2. A worked example of configuring EF Core

6.3. Configuring by conventions

6.3.1. Convention for entity classes

6.3.2. Conventions for parameters in an entity class

6.3.3. Name, type, and size conventions

6.3.4. By convention the Nullability of a property is based on .NET Type

6.3.5. An EF Core naming convention identifies primary keys

6.4. Configuring via Data Annotation

6.4.1. System.ComponentModel.DataAnnotations

6.4.2. System.ComponentModel.DataAnnotations.Schema

6.5. Configuring via Fluent API

6.5.1. A better way to structure your Fluent API commands

6.6. Excluding properties and classes from the database

6.6.1. Excluding a class or property via Data Annotations

6.6.2. Excluding a class or property via Fluent API

6.7. Configuring model-level query filters

6.8. Setting database column type, size, and nullability

6.9. The different ways of configuring the primary key

6.9.1. Configuring a primary key via Data Annotations

6.9.2. Configuring a primary key via Fluent API

6.10. Adding Indexes to database columns

6.11. Configuring the naming on the database side

6.11.1. Configuring table names

6.11.2. Configuring the schema name, and schema groupings

6.11.3. Configuring the database column names in a table

6.12. Using specific database provider Fluent API commands

6.13. Recommendations for using EF Core’s configuration

6.13.1. Use by convention configuration first – its quick and easy

6.13.2. Use Validation Data Annotation wherever possible

6.13.3. Use the Fluent API for anything else

6.14. Shadow properties – hide column data inside EF Core

6.14.1. Configuring Shadow properties

6.14.2. Accessing shadow properties

6.15. Backing fields – control access to data in an entity class

6.15.1. Creating a simple backing field accessed by a read/write property

6.15.2. Configuring backing fields

6.16. Summary

7. Configuring relationships

7.1. Defining some relationship terms

7.2. What navigational properties do I need in my entity class?

7.3. Configuring relationships

7.4. Configuring relationship by convention

7.4.1. What makes a class an entity class?

7.4.2. An example of an entity class with navigational properties

7.4.3. How EF Core finds foreign keys by convention

7.4.4. Nullability of foreign keys – required or optional relationships

7.4.5. Foreign keys – what happens if you leave them out?

7.4.6. When does the ‘by convention’ configuration not work?

7.5. Configuring relationships using Data Annotations

7.5.1. The ForeignKey Data Annotation

7.5.2. The InverseProperty Data Annotation

7.6. Fluent API relationship configuration commands

7.6.1. Creating a one-to-one relationship

7.6.2. Creating a one-to-many relationship

7.6.3. Creating a many-to-many relationship

7.7. Additional methods available in Fluent API relationships

7.7.1. OnDelete – changing the delete action of a dependent entity

7.7.2. IsRequired – defining the nullability of the foreign key

7.7.3. HasPrincipalKey – using an alternate unique key

7.7.4. Some of the less-used options on Fluent API relationships

7.8. Alternative ways of mapping entities to database tables

7.8.1. Owned types – a way to add a normal class into an entity class

7.8.2. Table-per-hierarchy (TPH) – placing inherited classes into one table

7.8.3. Table splitting – mapping multiple entity classes to the same table

7.9. Summary

8. Configuring advanced features and handling concurrency conflicts

8.1. Advanced feature – Using backing fields with relationships

8.1.1. The problem – the book app performance is too slow

8.1.2. My solution – IEnumerable<Review> property and a backing field

8.2. DbFunction - using user defined functions with EF Core

8.2.1. Configuration of a scalar user defined function (UDF)

8.2.2. Adding your UDF code to the database

8.2.3. Using a registered scalar UDF in your database queries

8.3. Computed column – a dynamically calculated column value

8.4. Setting a default value for a database column

8.4.1. Adding a constant as a default constraint

8.4.2. Adding a SQL fragment as a default constraint

8.4.3. Creating a value generator to generate a default value dynamically

8.5. Sequences - providing a known sequence of numbers

8.6. Marking database-generated properties

8.6.1. Marking a column that is generated on add or update

8.6.2. Marking a column as add on insert

8.6.3. Marking a column as “normal”

8.7. Handling simultaneous updates – concurrency conflicts

8.7.1. Why do concurrency conflicts matter?

8.7.2. EF Core’s concurrency conflict handling features

8.7.3. Handling a DbUpdateConcurrencyException

8.7.4. The disconnected concurrent update issue

8.8. Summary

9. Going deeper into the DbContext

9.1. Overview of the DbContext class’s properties

9.2. Understanding how EF Core tracks changes

9.3. Details on every command that changes an entity’s State

9.3.1. The Add command – creating a new entity/row in the database

9.3.2. The Remove command – deleting a row from the database

9.3.3. Modifying a tracked entity – EF Core’s DetectChanges

9.3.4. INotifyPropertyChanged entities – a different way of tracking changes

9.3.5. The Update method – telling EF Core that everything has changed

9.3.6. The Attach method – changing an untracked entity into a tracked entity

9.3.7. Setting the State of an entity directly

9.3.8. TrackGraph – handling disconnected updates with relationships

9.4. Using the ChangeTracker to detect changes

9.5. Using raw SQL commands in EF Core

9.5.1. The FromSql method – adding raw SQL to a EF Core query

9.5.2. The ExecuteSqlCommand method – execute a non-query command

9.5.3. The Reload method – useful after an ExecuteSqlCommand

9.5.4. The GetDbConnection method – calling database access commands

9.6. Context.Model – accessing EF Core’s view of the database

9.6.1. Using the Model property to build a fast database wipe method

9.7. Handling database connection problems

9.7.1. Handling database transaction with EF Core’s execution strategy

9.7.2. Altering or writing your own execution strategy

9.8. Summary

Part 3: Using Entity Framework Core in real-world applications

10. Using Entity Framework in real-world applications

10.1. Another look of separation of concerns principle

10.2. Using patterns to speed up databases access development

10.3. Speed up query development – use a LINQ Mapper

10.4. Domain-Driven Design database repository

10.4.1. Example Book DDD entity and repository

10.4.2. Impressions from building this DDD design

10.5. Is the Repository pattern useful with Entity Framework?

10.5.1. Some forms of repository patterns to avoid

10.6. Splitting a database across multiple DbContexts

10.6.1. Creating DbContext’s that only contain a subset of entities/tables

10.6.2. Passing data between bounded contexts

10.7. Data Validation and error handling patterns

10.7.1. Data Validation to your entity classes makes for better error feedback

10.7.2. Business logic should contain checks and return a list of all errors

10.7.3. Catching database server errors and providing user-friendly feedback

10.8. Summary

11. Handling database migrations

11.1. Part 1 – EF Core methods to change the database schema

11.1.1. A view of what databases need updating

11.2. Code-First: Using EF Core’s migrations

11.2.1. Stage 1: create a migration – building the code to do the migration

11.2.2. Stage 2 - applying migrations – updating a database schema

11.2.3. Undoing a migration(s) – Remove-Migration or update command

11.3. Database-First: Creating a DbContext from a database

11.4. SQL-First: Using SQL change scripts to change the schema

11.4.1. Using an SQL comparison tool to build an SQL change script

11.4.2. Using EfSchemaCompare to check your SQL matches EF Core’s Model

11.5. Part 2 – issues around a database schema change

11.5.1. Applying non-breaking changes while the current app is running

11.5.2. Applying a breaking database changes by stopping the application

11.5.3. Handling breaking database changes where I cannot stop the app

11.6. Summary

12. EF Core performance tuning

12.1. PART 1 - Deciding what performance issues to fix

12.1.1. “Don’t performance tune too early” doesn’t mean you stop thinking

12.1.2. How do you decide what is slow and needs performance tuning?

12.1.3. The cost of finding and fixing performance issues

12.2. PART 2 - techniques for diagnosing a performance issue

12.2.1. Stage 1: get a good overview - measuring the user’s experience

12.2.2. Stage 2. Find all the database code involved in the feature I am tuning

12.2.3. Stage 3. Inspecting the SQL code to find poor performance

12.2.4. Techniques for finding database scalability issues

12.3. PART 3 – techniques for fixing performance issues

12.4. Using good patterns makes your application perform well

12.4.1. Using Select loading to only load the columns you need

12.4.2. Using paging and/or filtering of searches to reduce the rows you load

12.4.3. A warning that using lazy loading will affect database performance

12.4.4. Always adding the AsNoTracking method to read-only queries

12.4.5. Using the async version of EF Core commands to improve scalability

12.4.6. Ensuring your database access code is isolated/decoupled

12.5. Performance anti-patterns: database access

12.5.1. Not minimizing the number of calls to the database

12.5.2. Calling SaveChanges multiple times

12.5.3. Allowing too much of a data query to be moved into the software side

12.5.4. Not replacing sub-optimal SQL translations with user defined functions

12.5.5. Not pre-compiling queries that are used frequently

12.5.6. Expecting EF Core to build the best SQL database commands

12.5.7. Not using the Find method when an entity might be already loaded

12.5.8. Missing Indexes from a property that you want to search on

Mismatching column data types === Performance anti-patterns: software ==== Making Detect Changes work too hard ==== Start-up issue: using one large DbContext === Performance patterns – scalability of database accesses ==== Using pooling to reduce the cost of a new application’s DbContext ==== Async/await – adding scalability, with small effect on speed ==== Helping your database scalability by making your queries simple ==== Picking the right architecture for applications that need high scalability === Summary

13. A worked example of performance tuning

13.1. PART 1a – making sure a single query performs well

13.1.1. Analyzing the book list query to see the potential performance issues

13.1.2. The book’s ‘Votes’ display was turned into a client-side calculation

13.2. PART 1b – improving the query by adding a DbFunction

13.2.1. Ensuring that the sorting and filtering in the query are performing well

13.3. PART 2 – Converting EF Core commands to SQL queries

13.3.1. A quick introduction to Dapper

13.3.2. Rewriting the MapBookToDto and associated EF queries using Dapper

13.4. PART 3 – Modifying the database to increase performance

13.4.1. Creating an ActualPrice property – changing the promotion process

13.4.2. Caching the book review values, and not letting them get out of date

13.4.3. Calculating an AuthorsString when a book is first created

13.4.4. An analysis of the changes – is the performance gain worth the effort?

13.5. An overall comparison of Parts 1a, 1b, 2, and 3

13.6. Database scalability – what can I do to improve that?

13.7. Summary

14. Different database types and EF Core services

14.1. What differences do other database server types bring?

14.1.1. Creating an instance of my application’s DbContext for MySQL

14.1.2. What I had to do to convert SQL Server application to MySQL

14.1.3. Looking at other database server types and differences

14.1.4. Summary on EF Core’s ability to work with multiple database types

14.2. Developing a CQRS architecture application with EF Core

14.2.1. My implementation of a two-database CQRS architecture application

14.2.2. How the various parts of my CQRS solution interacted with each other

14.2.3. Finding book view changes – part 1, finding the correct state and key

14.2.4. Finding the book view changes – part 2, building the correct state

14.2.5. Why the CQRS solution is less likely to have out-of-date cached values

14.2.6. Is the two-database CQRS architecture worth the effort?

14.3. Accessing and changing EF Core services

14.3.1. Accessing an EF Core service to help in your own application

14.3.2. Replacing an EF Core service with your own modified service

14.4. Accessing command-line tools from software

14.4.1. How to access EF Core design-time services

14.4.2. How I used design-time services to build my EfSchemaCompare tool

14.5. Summary

15. Unit testing EF Core applications

15.1. Introduction – my unit test setup

15.1.1. The test environment I am using – the xUnit unit test library

15.1.2. A library I have created to help with unit testing EF Core applications

15.2. Simulating the database when testing EF Core applications

15.2.1. The options you have for simulating the database

15.2.2. Choosing between in-memory or ‘real’ database for unit testing

15.3. Getting your application’s DbContext ready for unit testing

15.3.1. The application’s DbContext options are provided via its constructor

15.3.2. Setting an application’s DbContext options via OnConfiguring method

15.4. Simulating a database – using an in-memory database

15.5. Using a real database in your unit tests

15.5.1. How to set up a real database for a unit testing

15.5.2. Running unit tests in parallel – uniquely named databases

15.5.3. Tips on how to speed up the database creation stage of a unit test

15.5.4. How to handle databases where you have added extra SQL code

15.6. Unit testing a disconnected state update properly

15.7. Mocking a database repository pattern

15.8. Capturing EF Core logging information in unit testing

15.8.1. Using logging to help you build SQL change scripts

15.9. Using the EfSchemaCompare tool in your unit tests

15.9.1. The various features and options for the EfSchemaCompare tool

15.10. Summary


Appendix A: A brief introduction to LINQ

A.1. An introduction to the LINQ language

A.1.1. The two ways you can write LINQ queries

A.1.2. What data operations can you do with LINQ?

A.2. Introduction to IQueryable<T> type, and why it is useful

A.2.1. Splitting up a complex LINQ query using the IQueryable<T> type

A.2.2. How EF Core translates IQueryable<T> into database code

A.3. Querying an EF Core database using LINQ

A.4. Summary

About the book

Entity Framework Core in Action teaches developers how to add database functionality to .NET applications with EF Core. Part 1 starts with a clear introduction to what EF Core is and how it fits into your applications. Next, you'll get hands-on quickly by building a .NET application that uses a relational database with EF Core's default configuration. By the end of part 1 you will be able to build a well-structured application that uses EF Core for database access.

The second part of the book dives deeper and shows you how to change default settings as well as teaching you many EF Core commands. You'll learn how to create a database exactly the way you want it, as well as how to link to an existing database, and how to change the way database data is exposed inside your .NET application.

The last part is all about improving your skills and making you a better developer and debugger of EF Core applications. You'll learn from real-world applications of EF Core starting with a range of known patterns and practices that you can use, extending ER Core, and how to find and fix EF Core performance issues. Software developers who have never used Entity Framework and seasoned EF6.x developers, as well as anyone who wants to know what EF Core is capable of will find this book great at deepening their knowledge and making them more productive with EF Core.

What's inside

  • Querying a database
  • Creating, updating and deleting data
  • Using EF Core in business logic
  • Building a .NET web application EF Core

About the reader

This book assumes readers are familiar with .NET development and some understanding of what relational databases are. No experience with SQL needed.

About the author

Jon P Smith is a full-stack software developer and architect who focuses on Microsoft's ASP.NET web applications using Entity Framework (EF) ORM on the server-side, with various front-end JavaScript libraries. Jon is especially interested in defining patterns and building libraries that improve the speed of development of ASP.NET web/database applications.

Manning Early Access Program (MEAP) Read chapters as they are written, get the finished eBook as soon as it’s ready, and receive the pBook long before it's in bookstores.
MEAP combo $49.99 pBook + eBook + liveBook
MEAP eBook $39.99 pdf + ePub + kindle + liveBook

FREE domestic shipping on three or more pBooks