100% found this document useful (1 vote)
44 views

Get Practical Entity Framework Core 6: Database Access for Enterprise Applications Brian L. Gorman free all chapters

The document promotes the ebook 'Practical Entity Framework Core 6: Database Access for Enterprise Applications' by Brian L. Gorman, available for download on ebookmeta.com. It includes links to additional recommended digital products related to Entity Framework and other topics. The ebook covers various aspects of Entity Framework, including getting started, working with existing databases, and code-first development approaches.

Uploaded by

sineswedanag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
44 views

Get Practical Entity Framework Core 6: Database Access for Enterprise Applications Brian L. Gorman free all chapters

The document promotes the ebook 'Practical Entity Framework Core 6: Database Access for Enterprise Applications' by Brian L. Gorman, available for download on ebookmeta.com. It includes links to additional recommended digital products related to Entity Framework and other topics. The ebook covers various aspects of Entity Framework, including getting started, working with existing databases, and code-first development approaches.

Uploaded by

sineswedanag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Get the full ebook with Bonus Features for a Better Reading Experience on ebookmeta.

com

Practical Entity Framework Core 6: Database Access


for Enterprise Applications Brian L. Gorman

https://ebookmeta.com/product/practical-entity-framework-
core-6-database-access-for-enterprise-applications-brian-l-
gorman/

OR CLICK HERE

DOWLOAD NOW

Download more ebook instantly today at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Pro Entity Framework Core 2 for ASP.NET Core MVC 1st


Edition Adam Freeman

https://ebookmeta.com/product/pro-entity-framework-core-2-for-asp-net-
core-mvc-1st-edition-adam-freeman/

ebookmeta.com

Entity Framework Core in Action 2nd Edition Jon Smith

https://ebookmeta.com/product/entity-framework-core-in-action-2nd-
edition-jon-smith/

ebookmeta.com

Beginning Entity Framework Core 5 1st Edition Eric Vogel

https://ebookmeta.com/product/beginning-entity-framework-core-5-1st-
edition-eric-vogel/

ebookmeta.com

Infusion Therapy Standards of Practice 8th Edition Lisa A.


Gorski

https://ebookmeta.com/product/infusion-therapy-standards-of-
practice-8th-edition-lisa-a-gorski/

ebookmeta.com
2022 CFA Program Curriculum Level II Box Set vol 1 6 1st
Edition Cfa Institute

https://ebookmeta.com/product/2022-cfa-program-curriculum-level-ii-
box-set-vol-1-6-1st-edition-cfa-institute/

ebookmeta.com

Creative Haven Rose Windows Coloring Book: Create


Illuminated Stained Glass Special Effects (Creative Haven
Coloring Books) Avren
https://ebookmeta.com/product/creative-haven-rose-windows-coloring-
book-create-illuminated-stained-glass-special-effects-creative-haven-
coloring-books-avren/
ebookmeta.com

Routledge Handbook of War Law and Technology 1st Edition


James Gow (Editor)

https://ebookmeta.com/product/routledge-handbook-of-war-law-and-
technology-1st-edition-james-gow-editor/

ebookmeta.com

Leonard and Virginia Woolf The Hogarth Press and the


Networks of Modernism 1st Edition Helen Southworth

https://ebookmeta.com/product/leonard-and-virginia-woolf-the-hogarth-
press-and-the-networks-of-modernism-1st-edition-helen-southworth/

ebookmeta.com

Second Chances 1 4 1st Edition Lauren Wood

https://ebookmeta.com/product/second-chances-1-4-1st-edition-lauren-
wood/

ebookmeta.com
Rage Of Her Ravens Tara West

https://ebookmeta.com/product/rage-of-her-ravens-tara-west/

ebookmeta.com
Practical Entity
Framework
Core 6
Database Access for Enterprise Applications

Second Edition

Brian L. Gorman
Practical Entity
Framework Core 6
Database Access for Enterprise
Applications
Second Edition

Brian L. Gorman
Practical Entity Framework Core 6: Database Access for Enterprise Applications
Brian L. Gorman
Jesup, IA, USA

ISBN-13 (pbk): 978-1-4842-7300-5 ISBN-13 (electronic): 978-1-4842-7301-2


https://doi.org/10.1007/978-1-4842-7301-2

Copyright © 2022 by Brian L. Gorman


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.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Jonathan Gennick
Development Editor: Laura Berendson
Coordinating Editor: Jill Balzano
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media LLC, 1 New York Plaza, Suite
4600, New York, NY 10004. 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.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book's product page, located at www.apress.com/9781484273005. For more
detailed information, please visit http://www.apress.com/source-­code.
Printed on acid-free paper
This book is dedicated to my wife Cassie and
my children Kiera, Karson, Kreighton, and baby K who have
all made many sacrifices to give me the 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.
Table of Contents
About the Author��������������������������������������������������������������������������������������������������xxiii

About the Technical Reviewer�������������������������������������������������������������������������������xxv


Acknowledgments�����������������������������������������������������������������������������������������������xxvii

Introduction����������������������������������������������������������������������������������������������������������xxix

Part I: Getting Started������������������������������������������������������������������������������������� 1


Chapter 1: Introduction to Entity Framework����������������������������������������������������������� 3
One, two, three, four versions? Oh my!����������������������������������������������������������������������������������������� 3
When it all began��������������������������������������������������������������������������������������������������������������������� 4
ADO.Net – A better tool for application database interaction�������������������������������������������������� 5
A brief note about ADO.Net������������������������������������������������������������������������������������������������������ 5
Entity Framework makes its debut����������������������������������������������������������������������������������������������� 6
Entity Framework and LINQ����������������������������������������������������������������������������������������������������� 6
A new direction and a new visionary leader��������������������������������������������������������������������������������� 7
Microsoft goes all in for all developers����������������������������������������������������������������������������������� 7
A new vision requires a new path������������������������������������������������������������������������������������������� 7
What is .Net 5 and why is Entity Framework called EFCore5 instead of EF5, and
why are we already on .Net 6 and EFCore6����������������������������������������������������������������������������� 8
The state of the union�������������������������������������������������������������������������������������������������������������� 9
The future������������������������������������������������������������������������������������������������������������������������������������� 9
Activity 1-1: Getting started with EFCore6���������������������������������������������������������������������������������� 10
Task 1: Create a new project and add the EF packages�������������������������������������������������������� 10
Task 2: Add the EFCore6 packages to your project��������������������������������������������������������������� 15
Activity summary������������������������������������������������������������������������������������������������������������������� 25

v
Table of Contents

Chapter summary����������������������������������������������������������������������������������������������������������������������� 26
Important takeaways������������������������������������������������������������������������������������������������������������� 26
Closing thoughts�������������������������������������������������������������������������������������������������������������������� 26

Chapter 2: Working with an Existing Database������������������������������������������������������ 27


Reverse-engineering or database first��������������������������������������������������������������������������������������� 27
Why would we approach Entity Framework in this manner?������������������������������������������������ 27
Reverse-engineered solutions����������������������������������������������������������������������������������������������� 28
Keeping everything in sync��������������������������������������������������������������������������������������������������� 28
Interacting with the existing database���������������������������������������������������������������������������������� 29
Activity 2-0: Working with a pre-existing database�������������������������������������������������������������������� 29
Task 1: Prerequisites������������������������������������������������������������������������������������������������������������� 29
Task 2: Download and restore the backup file for the latest version of the
AdventureWorks database to your machine�������������������������������������������������������������������������� 32
Activity 2-1: Reverse-engineering an existing database with EFCore5�������������������������������������� 43
Task 1: Creating the solution with a new project and referencing the DBLibrary project����� 43
Task 2: Ensure .Net 6 and update all of the NuGet packages for both projects�������������������� 49
Task 3: Scaffold a new database context using the Scaffold-­Context command������������������ 55
Task 4: Create a settings file and leverage it from code������������������������������������������������������� 67
Task 5: Connect to the database and show results in code�������������������������������������������������� 74
Activity summary������������������������������������������������������������������������������������������������������������������������ 79
Chapter summary����������������������������������������������������������������������������������������������������������������������� 79
Important takeaways������������������������������������������������������������������������������������������������������������� 79
Closing thoughts�������������������������������������������������������������������������������������������������������������������� 79

Chapter 3: Entity Framework: Code First���������������������������������������������������������������� 81


Code first doesn’t always mean code first���������������������������������������������������������������������������������� 81
When not to use the code-first approach������������������������������������������������������������������������������ 81
When to use the code-first approach������������������������������������������������������������������������������������ 83
Code first in an existing project��������������������������������������������������������������������������������������������� 83
Code first in a new project against a mature database��������������������������������������������������������� 84
Code first in a new project with a new database������������������������������������������������������������������ 84

vi
Table of Contents

The benefits of a well-executed code-first development effort�������������������������������������������������� 84


Ability to get up and running quickly������������������������������������������������������������������������������������� 85
A complete record of database changes in source control��������������������������������������������������� 85
Agility when needing to revert to a previous state���������������������������������������������������������������� 86
Shifting from declarative to imperative database programming������������������������������������������� 87
It’s time to see code-first database programming in action������������������������������������������������������� 88
A final thought before diving into the activities��������������������������������������������������������������������� 88
Activity 3-1: Creating a new code-first project against an existing database in EFCore6���������� 89
Use the starter files or your project from Chapter 2�������������������������������������������������������������� 89
Task 1: Getting started with the activity�������������������������������������������������������������������������������� 90
Task 2: Creating and reviewing the initial migration������������������������������������������������������������� 93
Task 3: Comment out the initial migration, run the update, and review the database���������� 96
Task 4: Add a new migration, review it, remove it, and then add a real migration�������������� 102
Activity 3-1 summary���������������������������������������������������������������������������������������������������������������� 110
Activity 3-2: Creating a new code-first project in EFCore6������������������������������������������������������� 110
Task 1: Begin a new project for managing inventory���������������������������������������������������������� 111
Task 2: Add a new library for your database models – the “code” of code first����������������� 123
Task 3: Reference the InventoryModels project and use it to create a migration��������������� 127
Task 4: Update and review the database����������������������������������������������������������������������������� 135
Task 5: Add code to insert and query a list of items������������������������������������������������������������ 137
Activity 3-2 summary���������������������������������������������������������������������������������������������������������������� 143
Chapter summary��������������������������������������������������������������������������������������������������������������������� 143
Important takeaways����������������������������������������������������������������������������������������������������������� 144
Closing thoughts������������������������������������������������������������������������������������������������������������������ 144

Part II: Building the Data Solution�������������������������������������������������������������� 145


Chapter 4: Models and the Data Context�������������������������������������������������������������� 147
What is the database context and why do we need it?������������������������������������������������������������ 147
DBContext vs. ObjectContext����������������������������������������������������������������������������������������������� 148
What is the DBContext?������������������������������������������������������������������������������������������������������� 149
Constructing a new DBContext�������������������������������������������������������������������������������������������� 150

vii
Table of Contents

Critical properties and methods available when working with the DBContext������������������������� 152
Important properties on the DbContextOptionsBuilder object��������������������������������������������� 152
Important properties on the DBContextOptions object�������������������������������������������������������� 153
Important properties on the DBContext object�������������������������������������������������������������������� 153
Methods available on the DBContext����������������������������������������������������������������������������������� 154
Methods and extensions on the DBSet<TEntity> object����������������������������������������������������� 156
Working with models���������������������������������������������������������������������������������������������������������������� 157
Two immediate benefits of code-first models��������������������������������������������������������������������� 157
Building a database entity model���������������������������������������������������������������������������������������� 157
A final thought about models���������������������������������������������������������������������������������������������� 158
Activity 4-1: Modifying the Item model������������������������������������������������������������������������������������� 158
Practical application for your daily routine�������������������������������������������������������������������������� 159
Starter files�������������������������������������������������������������������������������������������������������������������������� 159
Task 1: Creating the base project���������������������������������������������������������������������������������������� 159
Task 2: Add properties to the Item class, and then use a migration to
update the database with fields to match the properties���������������������������������������������������� 166
Task 3: Add auditing to entities via inheritance������������������������������������������������������������������� 172
Activity 4-1 summary���������������������������������������������������������������������������������������������������������������� 178
Activity 4-2: Using the ChangeTracker to inject some automated auditing������������������������������ 179
Remember how you already set up the DBContext������������������������������������������������������������� 179
Common critical underlying objects������������������������������������������������������������������������������������ 180
The ChangeTracker is the lifeblood of our interaction with the Entity Framework�������������� 180
Task 1: Getting started��������������������������������������������������������������������������������������������������������� 180
Task 2: Use the change tracker to inject auditing information on calls to
save changes����������������������������������������������������������������������������������������������������������������������� 183
Task 3: Add an update method to validate last modified auditing is
working as expected����������������������������������������������������������������������������������������������������������� 189
Activity 4-2 summary���������������������������������������������������������������������������������������������������������������� 193
Chapter summary��������������������������������������������������������������������������������������������������������������������� 193
Important takeaways����������������������������������������������������������������������������������������������������������� 194
Closing thoughts������������������������������������������������������������������������������������������������������������������ 194

viii
Table of Contents

Chapter 5: Constraints, Keys, and Relationships�������������������������������������������������� 195


Constraining your data to enhance your solutions�������������������������������������������������������������������� 195
Size limitations�������������������������������������������������������������������������������������������������������������������� 196
Value constraints����������������������������������������������������������������������������������������������������������������� 198
Default values���������������������������������������������������������������������������������������������������������������������� 198
Other data annotations�������������������������������������������������������������������������������������������������������� 199
Using keys in database tables for unique and relational results���������������������������������������������� 200
Working with relational data����������������������������������������������������������������������������������������������������� 201
First, second, and third normal form����������������������������������������������������������������������������������� 201
First normal form (1NF)������������������������������������������������������������������������������������������������������� 202
Second normal form (2NF)�������������������������������������������������������������������������������������������������� 203
Third normal form (3NF)������������������������������������������������������������������������������������������������������ 205
Types of relationships���������������������������������������������������������������������������������������������������������� 207
One-to-one relationships����������������������������������������������������������������������������������������������������� 208
One-to-many relationships�������������������������������������������������������������������������������������������������� 209
Many-to-many relationships����������������������������������������������������������������������������������������������� 210
Some final thoughts about relationships and normalization����������������������������������������������� 212
Activity 5-1: Add length, range, and other constraints to the Item model��������������������������������� 212
Creating constraints������������������������������������������������������������������������������������������������������������ 212
Prerequisite: Get set up for this activity������������������������������������������������������������������������������ 213
Task 1: Setting length constraints on columns�������������������������������������������������������������������� 213
Task 2: Creating a range on numeric fields������������������������������������������������������������������������� 220
Task 3: Ensuring a field is a key, making fields required, and setting
default values on a column������������������������������������������������������������������������������������������������� 225
Task 4: Add a new migration and apply these changes to the database����������������������������� 228
Activity 5-1 summary���������������������������������������������������������������������������������������������������������������� 232
Activity 5-2: Working with relationships����������������������������������������������������������������������������������� 233
Creating a one-to-many relationship����������������������������������������������������������������������������������� 233
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 233
Task 1: Create the Categories in a one-to-many relationship with Items���������������������������� 234

ix
Table of Contents

Task 2: Create a one-to-one relationship from Category to CategoryDetail������������������������ 242


Task 3: Create a many-to-many relationship����������������������������������������������������������������������� 249
Activity 5-2 summary���������������������������������������������������������������������������������������������������������������� 256
Activity 5-3: Using a non-clustered, unique index�������������������������������������������������������������������� 256
Soft delete or hard delete, either way, just make sure it works������������������������������������������ 257
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 257
Task 1: Create the Genre����������������������������������������������������������������������������������������������������� 257
Task 2: Create the ItemGenre and the many-to-many relationship������������������������������������� 259
Task 3: Use the Index attribute to create a unique, non-­clustered index����������������������������� 263
Activity 5-3 summary���������������������������������������������������������������������������������������������������������������� 266
Chapter summary��������������������������������������������������������������������������������������������������������������������� 267
Important takeaways����������������������������������������������������������������������������������������������������������� 268
Closing thoughts������������������������������������������������������������������������������������������������������������������ 268

Chapter 6: Data Access (Create, Read, Update, Delete)���������������������������������������� 269


CRUD����������������������������������������������������������������������������������������������������������������������������������������� 269
LINQ������������������������������������������������������������������������������������������������������������������������������������� 269
Basic interactions��������������������������������������������������������������������������������������������������������������������� 269
Leverage the DbSet<T> objects������������������������������������������������������������������������������������������ 270
Common commands������������������������������������������������������������������������������������������������������������ 271
A final thought before diving into the activities������������������������������������������������������������������� 273
Activity 6-1: Quick CRUD with scaffolded controllers��������������������������������������������������������������� 273
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 274
Task 1: Creating the new MVC project��������������������������������������������������������������������������������� 274
Task 2: Start working with the ASP.Net MVC project����������������������������������������������������������� 282
Task 3: Create CRUD for the items��������������������������������������������������������������������������������������� 289
Activity 6-1 summary���������������������������������������������������������������������������������������������������������������� 296
Chapter summary��������������������������������������������������������������������������������������������������������������������� 296
Important takeaways����������������������������������������������������������������������������������������������������������� 297
Closing thoughts������������������������������������������������������������������������������������������������������������������ 297

x
Table of Contents

Chapter 7: Stored Procedures, Views, and Functions������������������������������������������� 299


Understanding stored procedures, views, and functions���������������������������������������������������������� 299
Stored procedures��������������������������������������������������������������������������������������������������������������� 300
Functions����������������������������������������������������������������������������������������������������������������������������� 300
Views����������������������������������������������������������������������������������������������������������������������������������� 301
Setting up the database to run scripts efficiently��������������������������������������������������������������������� 302
The problem������������������������������������������������������������������������������������������������������������������������ 302
The solution������������������������������������������������������������������������������������������������������������������������� 306
Fluent API���������������������������������������������������������������������������������������������������������������������������������� 307
What can you do with the Fluent API����������������������������������������������������������������������������������� 307
How do you work with the Fluent API���������������������������������������������������������������������������������� 307
Working with the database objects������������������������������������������������������������������������������������������� 309
A final thought before diving into the activities������������������������������������������������������������������� 309
Activity 7-1: Working with stored procedures��������������������������������������������������������������������������� 309
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 310
Task 1: Create a new stored procedure using inline code in your migration����������������������� 310
Task 2: Create the extension method to use local files for scripting����������������������������������� 316
Task 3: Apply the migration������������������������������������������������������������������������������������������������� 321
Task 4: Leverage the stored procedure in code������������������������������������������������������������������� 324
Activity 7-1 summary���������������������������������������������������������������������������������������������������������������� 331
Activity 7-2: Working with functions, the FluentAPI, and seed data������������������������������������������ 331
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 332
Task 1: Script out a new scalar-valued function������������������������������������������������������������������ 332
Task 2: Leverage the new function from code��������������������������������������������������������������������� 337
Task 3: Create a new table-valued function������������������������������������������������������������������������ 339
Task 4: Seed data with the Fluent API��������������������������������������������������������������������������������� 346
Task 5: Seed data with a custom solution��������������������������������������������������������������������������� 348
Task 6: Seed the Players and Items data����������������������������������������������������������������������������� 358
Activity 7-2 summary���������������������������������������������������������������������������������������������������������������� 363

xi
Table of Contents

Activity 7-3: Working with views����������������������������������������������������������������������������������������������� 364


Task 0: Getting started��������������������������������������������������������������������������������������������������������� 364
Task 1: Create the view������������������������������������������������������������������������������������������������������� 364
Task 2: Expose the view data from the UI layer������������������������������������������������������������������� 367
Activity 7-3 summary���������������������������������������������������������������������������������������������������������������� 370
Chapter summary��������������������������������������������������������������������������������������������������������������������� 370
Important takeaways����������������������������������������������������������������������������������������������������������� 371
Closing thoughts������������������������������������������������������������������������������������������������������������������ 371

Chapter 8: Sorting, Filtering, and Paging�������������������������������������������������������������� 373


It’s time to learn LINQ��������������������������������������������������������������������������������������������������������������� 373
LINQ is generally not the problem��������������������������������������������������������������������������������������� 373
Use a profiler or another tool����������������������������������������������������������������������������������������������� 374
Issues and solutions����������������������������������������������������������������������������������������������������������������� 374
Issue #1: Pre-fetching results and then iterating in code to filter the results��������������������� 375
Issue #2: Not disconnecting your data�������������������������������������������������������������������������������� 376
Issue #3: IEnumerable vs. IQueryable��������������������������������������������������������������������������������� 377
Practical application����������������������������������������������������������������������������������������������������������������� 378
Activity 8-1: Sorting, paging, and filtering��������������������������������������������������������������������������������� 379
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 379
Task 1: Compare the execution efficiency of two queries��������������������������������������������������� 381
Task 2: Filtering our results������������������������������������������������������������������������������������������������� 393
Task 3: Paging the filtered results��������������������������������������������������������������������������������������� 398
Task 4: Disconnecting the result sets���������������������������������������������������������������������������������� 401
Activity 8-1 summary���������������������������������������������������������������������������������������������������������������� 403
Chapter summary��������������������������������������������������������������������������������������������������������������������� 403
Important takeaways����������������������������������������������������������������������������������������������������������� 403
Closing thoughts������������������������������������������������������������������������������������������������������������������ 403

xii
Table of Contents

Part III: Enhancing the Data Solution���������������������������������������������������������� 405


Chapter 9: LINQ for Queries and Projections�������������������������������������������������������� 407
Data in the real world��������������������������������������������������������������������������������������������������������������� 407
LINQ vs. stored procedures������������������������������������������������������������������������������������������������� 407
Complex data and the code-first approach������������������������������������������������������������������������� 408
DTOs, view models, or domain models������������������������������������������������������������������������������������� 409
Decoupling your business or view logic from the database������������������������������������������������ 409
Sometimes, a pre-defined object is overkill������������������������������������������������������������������������ 410
One tool to rule them all����������������������������������������������������������������������������������������������������������� 411
AutoMapper������������������������������������������������������������������������������������������������������������������������� 412
Chapter 9 activities: Using LINQ, decoupled DTO classes, projections,
anonymous types, and AutoMapper������������������������������������������������������������������������������������������ 412
Activity 9-1: Working with LINQ in complex queries����������������������������������������������������������������� 413
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 413
Task 1: Get all the salespeople�������������������������������������������������������������������������������������������� 414
Task 2: Use projections to get more efficient queries��������������������������������������������������������� 422
Activity 9-1 summary���������������������������������������������������������������������������������������������������������������� 437
Activity 9-2: Setting up AutoMapper����������������������������������������������������������������������������������������� 438
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 438
Task 1: Get AutoMapper packages and configure the solution�������������������������������������������� 438
Task 2: Create the DTO objects�������������������������������������������������������������������������������������������� 441
Activity 9-2 summary���������������������������������������������������������������������������������������������������������������� 446
Activity 9-3: Working with AutoMapper������������������������������������������������������������������������������������� 446
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 447
Task 1: Perform a more advanced query����������������������������������������������������������������������������� 450
Task 2: Using AutoMapper and DTO projections������������������������������������������������������������������ 456
Activity 9-3 summary���������������������������������������������������������������������������������������������������������������� 461
Chapter summary��������������������������������������������������������������������������������������������������������������������� 462
Important takeaways����������������������������������������������������������������������������������������������������������� 462
Closing thoughts������������������������������������������������������������������������������������������������������������������ 462

xiii
Table of Contents

Chapter 10: Encryption of Data����������������������������������������������������������������������������� 463


Keeping your system’s data secure������������������������������������������������������������������������������������������ 463
Data at rest�������������������������������������������������������������������������������������������������������������������������� 463
Encryption in the past vs. encryption today������������������������������������������������������������������������ 463
Passwords��������������������������������������������������������������������������������������������������������������������������� 464
SSO via social logins����������������������������������������������������������������������������������������������������������� 464
ASP.Net built-in authentication�������������������������������������������������������������������������������������������� 464
Salting and hashing������������������������������������������������������������������������������������������������������������� 465
Protecting sensitive user information��������������������������������������������������������������������������������������� 466
Encryption basics���������������������������������������������������������������������������������������������������������������� 467
Which type should you use�������������������������������������������������������������������������������������������������� 467
Chapter 10 activities: Using Always Encrypted and Transparent Data Encryption�������������������� 469
Activity 10-1: Using Always Encrypted�������������������������������������������������������������������������������������� 469
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 469
Task 1: Enable Always Encrypted on the InventoryManagerDb������������������������������������������� 470
Activity 10-1 summary�������������������������������������������������������������������������������������������������������������� 491
Activity 10-2: Using Transparent Data Encryption��������������������������������������������������������������������� 491
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 492
Task 1: Plan the migration strategy������������������������������������������������������������������������������������� 493
Task 2: Create the backup columns������������������������������������������������������������������������������������� 495
Task 3: Create the keys and certificates������������������������������������������������������������������������������ 499
Task 4: Drop constraints on the targeted columns�������������������������������������������������������������� 502
Task 5: Drop the columns that are going to be targeted for encryption,
and then recreate them������������������������������������������������������������������������������������������������������� 506
Task 6: Select the backup data, transform it for encryption, and store it in
the original columns������������������������������������������������������������������������������������������������������������ 514
Task 7: Clean up the table��������������������������������������������������������������������������������������������������� 516
Activity 10-2 summary�������������������������������������������������������������������������������������������������������������� 517
Chapter summary��������������������������������������������������������������������������������������������������������������������� 517
Important takeaways����������������������������������������������������������������������������������������������������������� 517
Closing thoughts����������������������������������������������������������������������������������������������������������������������� 518
xiv
Table of Contents

Chapter 11: Repository and Unit of Work Patterns����������������������������������������������� 519


The repository (Repo) pattern��������������������������������������������������������������������������������������������������� 519
Sources of information about the repository pattern���������������������������������������������������������� 519
The repository pattern abstracts the database plumbing code from
the implementation������������������������������������������������������������������������������������������������������������� 520
Entity Framework’s built-in repository�������������������������������������������������������������������������������� 520
The unit of work pattern����������������������������������������������������������������������������������������������������������� 521
Using a unit of work������������������������������������������������������������������������������������������������������������ 521
Combining the repository and the unit of work������������������������������������������������������������������������ 521
The one-two punch������������������������������������������������������������������������������������������������������������� 522
A couple of drawbacks������������������������������������������������������������������������������������������������������������� 522
In general, rely on EF����������������������������������������������������������������������������������������������������������� 524
Separation of concerns������������������������������������������������������������������������������������������������������������� 524
Logical separation of concerns������������������������������������������������������������������������������������������� 524
Final benefits of separation of concerns����������������������������������������������������������������������������� 525
Chapter 11 activities����������������������������������������������������������������������������������������������������������������� 525
Activity 11-1: Layering your solution���������������������������������������������������������������������������������������� 525
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 526
Task 1: Creating the database layer������������������������������������������������������������������������������������ 526
Task 2: Creating the business layer������������������������������������������������������������������������������������� 530
Task 3: Create and implement database operations in the database layer������������������������� 531
Task 4: Create and implement business operations in the service layer���������������������������� 538
Task 5: Refactor the console program��������������������������������������������������������������������������������� 541
Activity 11-1 summary�������������������������������������������������������������������������������������������������������������� 546
Activity 11-2: Rolling your own UoW����������������������������������������������������������������������������������������� 546
Transactions are easy and effective������������������������������������������������������������������������������������ 546
Use the using statement for transaction lifecycles������������������������������������������������������������� 547
Task 0: Getting started��������������������������������������������������������������������������������������������������������� 547
Task 1: Modify the InventoryDatabaseLayer������������������������������������������������������������������������ 548
Task 2: Modify the InventoryBusinessLayer������������������������������������������������������������������������ 554

xv
Another Random Scribd Document
with Unrelated Content
Answer

20.
What word is that, of two syllables, to which if you prefix one
letter, two letters, or two other letters, you form, in each instance, a
word of one syllable?
Answer

21.
What was the favorite salad at the South, in the spring of 1861?
Answer

22.

There was a thing, ’twas two days old


Ere Adam was, of yore;
Before that thing was five weeks old,
Adam was years four-score.

Answer

23.

What’s that which on four limbs doth move


When first it sees the light,
But walks erect on two at noon,
And creeps on three at night?
Answer

24.

A sailor launched a ship of force,


A cargo put therein, of course;
No goods had he he wished to sell;
Each wind did serve his turn as well;
To neither port nor harbor bound,
His greatest wish to run aground.

Answer

25.

A merry maid, whose pleasant name


Was my sweet FIRST. Under a tree
She sat, and sang my THIRD, as free
As the wild crows, that without dread,
My SECOND called above her head.
Anon she turned, (with a last look
Above, below,) unto her book—
My WHOLE the author. Guess the same.

Answer

26.
The three most forcible letters in our alphabet?
Answer
27.
The two which contain nothing?
Answer

28.
The four which express great corpulence?
Answer

29.
The four which indicate exalted station?
Answer

30.
The three which excite our tears?
Answer

31.
What foreign letter is an English title?
Answer
32.
What foreign letter is a yard and a half long?
Answer

33.
What letter will unfasten an Irish lock?
Answer

34.
When was B the first letter of the alphabet, while E and O were
the only vowels?
Answer

35.
What letter is always more or less heavily taxed?
Answer

36.
What letter is entirely out of fashion?
Answer
37.
Why is praising people like a certain powerful opiate?
Answer

38.
Prove that a man has five feet.
Answer

39.

WHAT AM I?
I was once the harbinger of good to prisoners.
I add to the magnitude of a mighty river.
I am a small portion of a large ecclesiastical body.
I represent a certain form of vegetable growth.
A term used by our Lord in speaking to His disciples.
A subordinate part of a famous eulogy.
I am made useful in connection with the Great Western Railway.
Answer

40.

5005E1000E,

5005E1000E.
The name of a modern novel.
Answer

41.

Two words in French are often spoken;


Of home and love the fondest token:
But, strange to say it, one of these
Is English, from beyond the seas;
And though the thing seems quite absurd,
It means the same as t’other word.

Answer

42.

You fain would win fair Julia’s heart—


“Have I the power?” you’d ask her,
But, from your lips the words won’t part—
“’Tis not an easy task, Sir!”
“I know ’tis not, for one so shy.”
“Well, how shall I begin, Sir?”
“Be what you ask her,” I reply,
“And, ten to one, you’ll win, Sir!”

Answer

43.
My FIRST is company; my SECOND shuns company; my THIRD calls
together a company; and my WHOLE entertains company.
Answer
44.

My FIRST is a sound, of tranquillity telling,—


A cozy and complaisant sound for your dwelling.
A place which for criminals fittest is reckoned,
Yet where saints find ineffable peace, is my SECOND.
Or, where niggardly natures, who hunger and thirst
For the wealth of this world, keep their hearts, is my FIRST;
While my SECOND’S a measure you’ll know at a glance,
For ’tis shortest in Flanders, and longest in France.

Oh! my WHOLE is a name widely known, well beloved,


A name blessed on earth, and in Heaven approved;
Crowned by Faith and Good Works with so holy a light
That angels, themselves, thrill with joy at the sight.

Answer

45.
Dr. Whewell being asked by a young lady for his name “in cipher,”
handed her the following lines:

You 0 a 0, but I 0 thee,—


Oh, 0 no 0, but oh, 0 me;
And O, let my 0 no 0 go,
But give 0 0 I 0 you so!

Answer

46.
Why was the execution of Charles the First voluntary on his part?
Answer

47.
How is Poe’s “Raven” shown to have been a very dissipated
bird?
Answer

48.
Set down four 9’s so as to make one hundred.
Answer

49.
The cc 4 put 00000000.
si
Answer

50.
John Doe to Richard Roe, Dr.
To 2 bronze boxes $3 00
1 wooden do 1 50
1 wood do 1 50
——

This bill was canceled by the payment of $1.50. How?


Answer
51.
When was Cowper in debt?
Answer

52.
What animal comes from the clouds?
Answer

53.

My FIRST is one of mystic three,


Who go where goes true Liberty;
Sets with the sun, with him to rise,
Lives in the flame and with it dies;
Fades with the leaf that earthward flies.

My SECOND cleaves the morning air,


Floats through the evening still and fair;
Now soars beyond the mountain crest,
Now flutters downward to its rest,
Now broods upon some hidden nest.

My WHOLE long since the prairie trod,


Now rests beneath the prairie-sod;
Yet still upon the river stands,
And calls the stranger to the lands
Which Reminichia’s[1] cliff commands.

Answer
54.

I saw a peacock with a fiery tail


I saw a blazing comet pour down hail
I saw a cloud all wrapt with ivy ’round
I saw a lofty oak creep on the ground
I saw a beetle swallow up a whale
I saw the foaming sea brimful of ale
I saw a pewter cup sixteen feet deep
I saw a well full of men’s tears that weep
I saw wet eyes in flames of living fire
I saw a house as high as the moon and higher
I saw the glorious sun at deep midnight
I saw the man who saw this wondrous sight!

An incredulous friend actually ventured to doubt the above plain


statement of facts, but was soon convinced of its literal truth.
Answer

55.
Charles the First walked and talked half an hour after his head
was cut off.
Answer

56.
At the time of a frightful accident, what is better than presence of
mind?
Answer
57.
Why was the year preceding 1871 the same as the year following
it?
Answer

58.
Why do “birds in their little nests agree?”
Answer

59.
What did Io die of?
Answer

60.
Why did a certain farmer out West name his favorite rooster
ROBINSON?
Answer

61.
How do sailors know there’s a man in the moon?
Answer
62.
How do sailors know Long Island?
Answer

63.
What does a dog wear in warm weather, besides his collar?
Answer

64.

If you transpose what ladies wear,


’Twill plainly show what bad men are:
Again, if you transpose the same,
You’ll see an ancient Hebrew’s name:
Change it again and it will show,
What all on earth desire to do.

Answer

65.

Two brothers, wisely kept apart,


Together ne’er employed;
Though to one purpose we are bent,
Each takes a different side.

To us no head nor mouth belongs,


Yet plain our tongues appear;
With them we never speak a word,
Without them, useless are.

In blood and wounds we deal, yet good


In temper we are proved;
From passion we are always free,
Though oft with anger moved.

We travel much, yet prisoners are,


And close confined, to boot;
Can with the swiftest horse keep pace,
Yet always go on foot.

Answer

66.
Translate:
Je suis capitaine de vingt-cinq soldats; et, sans moi, Paris serait
pris.
Answer

67.
Je suis ce que je suis, et je ne suis pas ce que je suis. Si j’étais
ce que je suis, je ne serais pas ce que je suis.
Answer

68.

Mus cucurrit plenum sed


Contra meum magnum ad!
Answer

69.
Mens tuum ego!
Answer

70.
The title of a book: Castra tintinnabula Poëmata.
Answer

71.
Motto on a Chinese box: Tu doces!
Answer

72.

Answer
73.
Translate:
Quis crudus enim lectus, albus, et spiravit!
Answer

74.
Ecrivez: “J’ai grand appétit,” en deux lettres.
Answer

75.

Monosyllabic I, and a reptile, I trow;


But, cut me in twain, I form syllables two.
I’m English, I’m Latin, the one and the other;
And what’s Latin for one half, is English for t’other.

Answer

76.

Ever running on my race,


Never staying in one place,
Through the world I make my tour
Everywhere at the same hour.
If you please to spell my name,
Backward, forward, ’tis the same.

Answer
77.
In my FIRST my SECOND sat; my THIRD and FOURTH I ate; and yet I
was my WHOLE.
Answer

78.

TONIS A DRESTO MARE.


O Mare! Eva si formæ,
Formæ ure tonitru;
Iambicum as amandum,
Olet Hymen promptu!
Mihi his vetas annæ se,
As humano erebi;
Olet mecum, mare, to te,
Or Eta Beta Pi.

Alas, plano more meretrix;


Mi ardor vel uno,
Inferiam ure artis base
Tolerat me urebo.
Ah me! ve ara scilicet
To laudu vimin thus.
Hiatu as arandum sex—
Illuc Ionicus!

Heu! sed heu! vixin, imago,


Mi missis mare sta!
O cantu redit in mihi
Hibernus arida?

Everi dafur heri si;


Mihi resolves indu;
Totius, olet Hymen cum
Accepta tonitru!

Answer

79.

From these five squares take three of the


fifteen sides, and leave three squares.
Answer

80.

Divide this figure into four equal and


uniform parts.
Answer

81.

Four things there are all of a height,


One of them crooked, the rest upright.
Take three away, and you will find
Exactly ten remains behind:
But, if you cut the four in twain,
You’ll find one-half doth eight retain.

Answer

82.
To divide eight gallons of vinegar equally between two persons;
using only an eight-gallon, a five-gallon, and a three-gallon
measure?
Answer

83.
A certain miller takes “for toll” one tenth of the meal or flour he
grinds. What quantity must he grind in order that a customer may
have just a bushel of meal after the toll has been taken?
Answer

84.
To prove that two are equal to one:
Let x = a: Then, x2 = ax,
x2 − a2 = ax − a2,
(x + a)(x − a) = a(x − a),
x + a = a,
2a = a,
2 = 1. Q. E. D.
Where is the fallacy?
Answer

85.
As two Arabs, who had for sole provision, the one five, and the
other three loaves of bread, were about to take their noonday meal
in company, they were joined by a stranger who proposed to
purchase a third part of their food. In payment he gave them, when
their repast was finished, eight pieces of silver, and they, unable to
agree as to the division of the sum referred the matter to the nearest
Cadi, who gave seven pieces to the owner of the five loaves, and but
one piece to the owner of the three loaves. And the Cadi was right.
Answer

86.
A man went to a store and bought a pair of boots for six dollars.
He put down a ten dollar bill, and the merchant having no change,
sent for it to a neighboring bank, and gave it to him. Later in the day
one of the bank clerks came in to say that the ten dollar bill was a
bad one, and insisted that the merchant should make it right, which
he did. Now, how much did he lose by the whole transaction?
Answer

87.
A man bought twelve herrings for a shilling; some were two
pence apiece, some a halfpenny, and some a farthing. How many
did he buy of each kind?
Answer

88.

My FIRST is the last of me;


My SECOND is not so much;
And my WHOLE is entirely destitute of my FIRST.

Answer

89.

There is a word of plural number,


A foe to peace and tranquil slumber;
Now, any word you chance to take,
Adding an s will plural make;
But if you add an s to this,
How strange the metamorphosis!
Plural is plural then no more,
And sweet what bitter was before.

Answer

90.

“Charge, Chester, charge! On, Stanley, on!”


Were the last words of Marmion.
Had I been in Stanley’s place,
When Marmion urged him to the chase,
You then would very soon descry,
What brings a tear to every eye.

Answer

You might also like