Brian L. Gorman

Practical Entity Framework

Database Access for Enterprise Applications

1st ed.
Brian L. Gorman
Jesup, IA, USA
ISBN 978-1-4842-6043-2e-ISBN 978-1-4842-6044-9
© Brian L. Gorman 2020
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use.
The publisher, the authors and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, expressed or implied, with respect to the material contained herein or for any errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

This book is dedicated to my wife Cassie and my children Kiera, Karson, and Kreighton, who have all made many sacrifices to give me space and time to write, as well as for your daily, unceasing love, grace, patience, and encouragement.

This book is further dedicated to you, dear reader. Thank you for allowing me to be part of your journey to greatness.

Introduction

Entity Framework is the ORM of choice for .Net development for a majority of enterprise application development teams. Through the years, EF has gone through a number of changes, and the move into the .Net Core world has seen EF become more performant and more user-friendly.

As this book begins, we’ll take a look at the state of things as they are, and the state of things to come. In the first couple of chapters, we’ll even look at differences in approaches to working with EF, whether you are working with EF6 or EFCore. We’ll touch on the two different approaches to working with the database: database first and code first. After the first three chapters, we settle in on the code-first approach with EFCore.

The great news is that no matter what approach to the database or version of EF you are using, with just a few minor exceptions, things will generally work in a similar fashion, so all of the information in this book is relevant to anyone working with Entity Framework.

Who this book is for

Practical Entity Framework is written for anyone that is new to Entity Framework or is still learning and wants to become much better with Entity Framework.

If you are already an expert or a well-established developer with a few years of EF under your belt, this book will likely not have a lot of new information for you.

Overall, the book is designed to work through the moving pieces that are necessary to understand and work with EF, as well as how to approach architecting SOLID solutions around EF. The practical nature of each activity will give you many examples and cover a lot of the basic and advanced topics you will likely encounter in real-world applications.

How this book is structured and what is covered in the chapters

This book has been developed into four parts. Part 1 contains the first three chapters and covers many of the introductory topics and contrasts in approaches to using the database in EF. Part 2, which includes Chapters 410, is about building out the database solution and covers core operations for the code-first approach to working with EF. Part 3 includes Chapters 1113 and covers critical ways to enhance your solutions. Part 4 includes Chapters 14 and 15 and discusses more recipes for success and a look into the future of EF.

Part 1 – Getting Started

Chapter 1, “Introduction to Entity Framework,” begins by discussing the current state of enterprise applications with Entity Framework. In the chapter, we take a look at how to get set up and start building out a solution with Entity Framework.

Chapter 2, “Working with an Existing Database,” discusses the approach developers might need to take if there is already an established database and the solution needs to use EF. The chapter uses a copy of the AdventureWorks database and covers how to work with the EFCore tools to reverse engineer a database, as well as how to use the database-first approach in EF6.

Chapter 3, “Entity Framework: Code First,” starts with a discussion of what it means to be code first and when it may not make sense to use the approach, and then quickly moves into the benefits of using a code-first approach. The activities walk through implementing a code-first approach in EFCore and EF6.

Part 2 – Building the Data Solution

Chapter 4, “Models and the Data Context,” covers working with our entities to build out the objects that represent the tables in the database and then execute the migrations to make sure the tables exist as defined in code. The activities in this chapter reinforce that learning.

Chapter 5, “Constraints, Keys, and Relationships,” takes a look at how to set the primary keys, multiple column keys, and database relationships that you will likely encounter. The activities cover setting up constraints, index, and relationships in EFCore.

Chapter 6, “Data Access (Create, Read, Update, Delete),” is a critical chapter to learn how to do the CRUD operations against your database. In the activity for this chapter, we spin up a website and see how quickly we can build out CRUD operations.

Chapter 7, “Stored Procedures, Views, and Functions,” continues our learning of practical applications of EF with a good luck at what it takes to incorporate database objects into the code-first solution. The activities cover setting up and working with stored procedures, functions, views, and seeding data.

Chapter 8, “Sorting, Filtering, and Paging,” takes a deeper dive into working with LINQ to get data and ensuring that our operations are as efficient as possible with EF. The activity for the chapter walks through sorting, filtering, and paging the data, as well as looking at working with a disconnected dataset.

Chapter 9, “LINQ for Queries and Projections,” introduces the valuable use of projections in our queries and also covers using AutoMapper in our solution. The activities get us started with projections and then implement AutoMapper into our solution.

Chapter 10, “Encryption of Data,” takes a look at the two main ways to encrypt our data – either through the AlwaysEncrypted built-in approach or through a customized approach using certificates and keys to encrypt or decrypt our data.

Part 3 – Enhancing the Data Solution

Chapter 11, “Repository and Unit of Work Patterns,” takes a look at two of the more critical patterns around working with data and ORMs. Although EF has built-in repository (repo) and unit of work (UoW) patterns, sometimes we need to have a bit more flexibility. The activities for this chapter involve refactoring our code into layers and then implementing our own UoW.

Chapter 12, “Unit Testing, Integration Testing, and Mocking,” discusses the importance of unit testing and integration testing, as well as what it means to mock data. The activities enhance our learning around mock data, as well as implement unit tests and integration tests.

Chapter 13, “Alternatives to Entity Framework: Dapper,” provides information on how we can wire up a lightweight ORM to enhance our query performance. The activities for the chapter build out the ability to see the selection of data from Dapper.

Part 4 – Recipes for Success

Chapter 14, “Asynchronous Data Operations and Multiple Database Contexts,” begins by refactoring everything to use the async/await pattern for leveraging the threading operations in our solutions. The chapter concludes with a look at what it takes to work with multiple databases, including the mandatory use of the fully qualified context name in order to generate or run database migrations.

Chapter 15, “.Net 5 and Entity Framework,” concludes our book with a forward-looking chapter, in that here we take a first look into what is coming in the vNext (EFCore5) version of Entity Framework.

Code samples and exercises

This book is designed to be a training manual for information and the practical use of Entity Framework. Therefore, each chapter has from one to three workable activities. To get the most out of this book, you are encouraged to work through each example. To aid you in this process, I have provided a starter and a final pack for each activity. You can download the code resources from the book’s catalog page on Apress.com to find downloads. The code is available at github.com/Apress/practical-entity-framework.

Connect with the author

I would love to hear from you and/or connect with you. I am especially interested in any thoughts you have around the book, ways I could have improved it, and/or any errors you find through your learning journey. Please don’t hesitate to connect with me on LinkedIn or Twitter. I reserve Facebook connections to people that I know, so please don’t try to connect with me there. I can also be reached via email.

LinkedIn: www.linkedin.com/in/brianlgorman/

Twitter: https://twitter.com/blgorman

Email: [email protected]

Acknowledgments

I would not have been able to write this book if it were not for a number of people who have both influenced and helped me throughout my career, as well as the multitudes of grace and support that I have received from my family throughout this process.

I’d like to begin by thanking the partners and team members at Far Reach. Thank you, Kate Washut, Jason Nissen, Lana Wrage, Chris Rouw, and Chad Feldmann for allowing me to flex and reduce hours to continue to work on projects like this one and to all the team at Far Reach for helping me to learn and grow in both tech and soft skills and for generally having as much fun as possible at work for the last four years.

A special thanks as well to Andre van Meulebrouck for his excellent work as a technical reviewer and editor. Andre’s thoughts and comments throughout the process have greatly helped to shape this book. Also, his incredible patience with working through a couple of bugs with the solution files has been an invaluable resource to help ensure the resources work and the directions are easy to follow. An extra special thanks to Andre as well for consistently putting up with my misuse of setup vs. set up.

I’d also like to thank the many friends and acquaintances I’ve made at various tech conferences in the past few years. I’ve learned so much from all of you. There are a few that I must mention, however. First, Mike Cole, my peer and friend, thank you for introducing me to AutoMapper projections, and thanks for all your candid conversations around EF with me as I wrote this book. Thanks to Mitchel Sellers for your talk on Entity Framework that I got to see at Iowa Code Camp and again at our CVINETA meeting addressing the performance pitfalls that arise from misusing Language Integrated Query (LINQ). Thanks, Jonathan “J” Tower, for your awesome talk on ORMLite and Dapper at Codemash, which solidified my thoughts on including a chapter on the topic in this book.

Thank you to Apress and the team who have believed in me and have helped to make this book possible. Thanks to Jonathan Gennick and Jill Balzano for running the project, editing, and overseeing the entire schedule and process.

I would be remiss if I didn’t also thank Dustin Behn, the leader of the Inspired Nation, and his life coaching and his Emergence program. Thank you for coaching me these past few years and for helping me get out of my own way to do things like this book.

Last, and most importantly, to my wife Cassie and our kids, to whom the book is also dedicated. Thank you for giving me time and space to make this book happen and for continually checking on my progress by asking how many chapters I have done and how many I have left.

Table of Contents
Part I: Getting Started
Part II: Building the Data Solution
Part III: Enhancing the Data Solution
Index 639
About the Author
Brian L. Gorman
../images/491632_1_En_BookFrontmatter_Figb_HTML.jpg
is a developer, computer science instructor, and trainer and has been working in .NET technologies as long as they have existed. He was originally MCSD certified in .NET 1 and has recently recertified with MCSA: Web Apps, and MCSD: App Builder certifications. Additionally, he became an MCT as of April 2019 and is focusing on developing and training developers with full-stack web solutions with .NET Core and Azure. In addition to working with .NET technologies, Brian also teaches computer science for Franklin University, where his courses taught have included data structures, algorithms, design patterns, and, more recently, full-stack enterprise solutions in the capstone practicum course. In July 2020, due to COVID-19, Brian decided to host an online virtual developer conference called SciFiDevCon.

Brian also has a passion for music and has been writing and releasing original Christian music for the last six years. His music can be found online at any of the major streaming venues such as Spotify or iTunes.

Brian currently lives in Eastern Iowa with his wife and three young children.

 
About the Technical Reviewer
André van Meulebrouck
../images/491632_1_En_BookFrontmatter_Figc_HTML.jpg
has a keen interest in functional programming, especially Haskell and F#.

He also likes data technologies from markup languages to databases and F# type providers.

He lives in Southern California with his wife “Tweety”, and is active in athletics: hiking, mountain biking, and gravity/balance sports like freestyle skating (inline and ice), skateboarding, surfing, and sandboarding.

To keep his mind sharp, he does compositional origami, plays classical guitar, and enjoys music notation software.

 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.199.243