Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $9.99/month after trial. Cancel anytime.

Entity Framework Core Cookbook - Second Edition
Entity Framework Core Cookbook - Second Edition
Entity Framework Core Cookbook - Second Edition
Ebook762 pages3 hours

Entity Framework Core Cookbook - Second Edition

Rating: 0 out of 5 stars

()

Read preview

About this ebook

This book is for .NET developers who work with relational databases on a daily basis and understand the basics of Entity Framework, but now want to use it in a more efficient manner. You are expected to have some prior knowledge of Entity Framework.
LanguageEnglish
Release dateNov 9, 2016
ISBN9781785880582
Entity Framework Core Cookbook - Second Edition

Related to Entity Framework Core Cookbook - Second Edition

Related ebooks

Programming For You

View More

Related articles

Reviews for Entity Framework Core Cookbook - Second Edition

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Entity Framework Core Cookbook - Second Edition - Ricardo Peres

    Table of Contents

    Entity Framework Core Cookbook - Second Edition

    Credits

    About the Author

    About the Reviewer

    www.PacktPub.com

    eBooks, discount offers, and more

    Why subscribe?

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Sections

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Improving Entity Framework in the Real World

    Introduction

    Improving Entity Framework by using a code-first approach

    Getting ready

    How to do it…

    How it works…

    There's more…

    Convention over configuration

    Model-View-Controller

    Single Responsibility Principle

    Provider Model

    Testing

    See also

    Unit testing and mocking

    Getting ready

    How to do it…

    How it works…

    There's more…

    One class under test

    Integration tests

    Arrange, Act, Assert

    Mocking

    Creating databases from code

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Creating mock database connections

    How to do it…

    How it works…

    See also

    Implementing the repository pattern

    Getting ready

    How to do it…

    How it works…

    There's more…

    Dependency Inversion Principle

    Repository and caching

    Mocking

    Where generic constraint

    See also

    Implementing the unit of work pattern

    Getting ready

    How to do it…

    How it works…

    There's more…

    Call per change

    Interface Segregation Principle

    Refactoring

    See also

    2. Mapping Entities

    Introduction

    Mapping non-public members

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Mapping interfaces

    Getting ready

    How to do it…

    How it works…

    See also

    Shadow properties

    Getting ready

    How to do it…

    How it works…

    See also

    Creating one-to-one maps

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Creating one-to-many maps

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Creating many-to-many maps

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Creating custom conventions

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Using sequence key generators

    Getting ready

    How to do it…

    How it works...

    There's more…

    See also

    Using GUIDs as keys

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Implementing inheritance – Table per Class hierarchy

    Getting ready

    How to do it…

    How it works…

    There's more…

    3. Validation and Changes

    Introduction

    Validating simple properties

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Validating the whole entity

    Getting ready

    How to do it…

    How it works…

    See also

    Validating groups of entities

    How to do it…

    How it works…

    See also

    Intercepting saving changes

    Getting ready

    How to do it…

    How it works…

    See also

    Intercepting property changes

    Getting ready

    How to do it…

    How it works…

    See also

    Setting the state of an entity

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Improving MVC UI with entity framework validation

    Getting ready

    How to do it…

    How it works…

    There's more…

    Understanding the HTML helper

    See also

    Inserting, updating, and deleting entities with stored procedures

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Updating the database from model changes

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Dumping the SQL script for the database creation

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    4. Transactions and Concurrency Control

    Introduction

    Using explicit transactions

    Atomic

    Consistent

    Isolation

    Durability

    Getting ready

    How to do it…

    How it works…

    See also

    Using transactions in custom SQL operations

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Implementing optimistic concurrency in SQL Server

    Getting ready

    How to do it…

    How it works…

    There's more…

    Database wins

    Client wins/last one wins

    See also

    Implementing optimistic concurrency in a database-agnostic way

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    5. Querying

    Introduction

    Executing client-side functions in LINQ queries

    Getting ready

    How to do it…

    How it works…

    See also

    Mixing SQL with LINQ queries

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Getting entities from the local cache

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Creating filtered collections

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Creating reusable queries

    Getting ready

    How to do it…

    How it works…

    There's more…

    Extension methods

    Naming conflict

    See also

    Querying shadow properties

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Implementing the query object pattern

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Using dynamic LINQ

    Getting ready

    How to do it…

    How it works…

    There's more…

    6. Advanced Scenarios

    Introduction

    Generating entities from the database

    Getting ready

    How to do it…

    How it works…

    There's more…

    Implementing multitenancy

    Getting ready

    How to do it…

    How it works…

    There's more…

    Strongly typed bulk operations

    Getting ready

    How to do it…

    How it works…

    There's more…

    Handling soft deletes

    Getting ready

    How to do it…

    How it works…

    See also

    Adding logging

    Getting ready

    How to do it…

    How it works…

    There's more…

    Capturing the audit data

    Getting ready

    How to do it…

    How it works…

    See also

    Retrieving entity metadata

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Improving MVC applications

    Getting ready

    How to do it.…

    See also

    Hooking infrastructure services

    Using other databases

    How to do it…

    7. Performance and Scalability

    Introduction

    Improving the performance of queries

    Getting ready

    How to do it…

    Modifications

    Updates

    Deletes

    Queries

    SQL

    LINQ

    See also

    Testing and profiling queries

    How to do it…

    Logging

    Database profiler

    Real time monitoring

    Testing

    See also

    Using asynchronous operations

    Getting ready

    How to do it…

    Queries

    Modifications

    See also

    Eager loading

    Getting ready

    How to do it…

    How it works…

    See also

    Using the cache

    Getting ready

    How to do it…

    How it works…

    There's more…

    A. Pitfalls

    Introduction

    GroupBy executes on the client side

    Problem

    How to fix it…

    Table per class hierarchy requires nullable columns for derived classes

    Problem

    How to solve it…

    References not eagerly fetched are lost

    Problem

    How to solve it…

    Date/time operations are not supported

    Problem

    How to solve it…

    Paging in SQL Server earlier than 2012

    Problem

    How to solve it…

    Database null semantics

    Problem

    How to solve it…

    Migrations and contexts with parameterized constructors

    Problem

    How to solve it…

    Migrations with contexts in different projects

    Problem

    How to solve it…

    Accessing the service provider too soon

    Problem

    How to solve it…

    Setting the maximum string length

    Problem

    How to solve it…

    Mapping discriminator columns

    Problem

    How to solve it…

    Composite primary keys

    Problem

    How to solve it…

    Refreshing entities

    Problem

    How to solve it…

    Cascading entity deletes

    Problem

    How to solve it…

    Index

    Entity Framework Core Cookbook - Second Edition


    Entity Framework Core Cookbook - Second Edition

    Copyright © 2016 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: March 2012

    Second edition: November 2016

    Production reference: 1031116

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78588-330-9

    www.packtpub.com

    Credits

    Author

    Ricardo Peres

    Reviewer

    Jason De Oliveira

    Commissioning Editor

    Kunal Parikh

    Acquisition Editor

    Chaitanya Nair

    Content Development Editors

    Siddhi Chavan

    Merint Mathew

    Technical Editors

    Bhavin Savalia

    Dhiraj Chandanshive

    Copy Editor

    Safis Editing

    Project Coordinator

    Suzanne Coutinho

    Proofreader

    Safis Editing

    Indexer

    Tejal Daruwale Soni

    Graphics

    Abhinash Sahu

    Production Coordinator

    Melwyn Dsa

    Cover Work

    Melwyn Dsa

    About the Author

    Ricardo Peres is a Portuguese developer, blogger, and occasionally an e-book author. He has more than 17 years of experience in software development, using technologies such as C/C++, Java, JavaScript, and .NET. His interests include distributed systems, architectures, design patterns, and general .NET development.

    He currently works for London-based Simplifydigital as a technical evangelist, and was first awarded as MVP in 2015.

    Ricardo maintains a blog, Development With A Dot, where he regularly writes about technical issues. You can read it here: http://weblogs.asp.net/ricardoperes.

    He has reviewed Learning NHibernate 4 for Packt.

    You can catch up with him at @RJPeres75.

    I'd like to thank my family, Zézinha, Francisco, and Madalena, for their love and patience and my friends and colleagues at Simplifydigital for all their support.

    This book is dedicated to my parents, Irene (1947-2005) and Jorge Peres (1941-2015), with love and saudades.

    About the Reviewer

    Jason De Oliveira works as a CTO for MEGA International (http://www.mega.com), a software company in Paris (France) that provides modeling tools for enterprise architecture, enterprise governance risk, and compliance management. He is an experienced manager and senior solutions architect with a lot of skills in software architecture and enterprise architecture.

    He loves sharing his knowledge and experience via his blog, by speaking at conferences, writing technical books, writing articles in the technical press, giving software courses as MCT, and coaching co-workers in his company. He frequently collaborates with Microsoft, and you can quite often find him at the Microsoft Technology Center (MTC) in Paris. Microsoft awarded him in 2011 with an MVP in C# for his numerous contributions to the Microsoft community. Microsoft seeks to recognize the best and brightest from technology communities around the world with the MVP award. These exceptional and highly-respected individuals come from more than 90 countries, serve their local online and offline communities, and have an impact worldwide. Jason is very proud to be one of them. Please feel free to contact him via his blog (http://www.jasondeoliveira.com) if you need any technical assistance or want to discuss technical subjects.

    Jason has worked as a reviewer on .NET 4.5 Expert Programming Cookbook, WCF 4.5 Multi-tier Services Development with LINQ to Entities, .NET 4.5 Parallel Extensions Cookbook, and WCF 4.5 Multi-layer Services Development with Entity Framework, Third Edition by Packt. He has also worked as an author on Visual Studio 2013: Concevoir, développer et gérer des projets Web, les gérer avec TFS 2013 by Editions ENI.

    I would like to thank my lovely wife, Orianne, and my beautiful daughters, Julia and Léonie, for supporting me in my work and for accepting long days and short nights during the week and sometimes even during the weekend. My life would not be the same without them!

    www.PacktPub.com

    eBooks, discount offers, and more

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www.packtpub.com/mapt

    Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as ind]ustry-leading tools to help you plan your personal development and advance your career.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Preface

    This book is about the new Entity Framework Core 1.0. In here, you will find recipes that will hopefully make your life easier when working with Entity Framework Core. If all goes well, you will also have some fun while doing it.

    It has something for both beginners as well as more seasoned developers.

    What this book covers

    Chapter 1, Using Entity Framework in the Real World, introduces you to the structure of the sample project, and we will see some examples of how to use Entity Framework in a real MVC application.

    Chapter 2, Mapping Entities, presents the way to configure the mapping of entities and properties and relations between entities.

    Chapter 3, Validation and Changes, talks about how Entity Framework detects modifications made to entities, and how we can intercept those modifications, or apply our custom validation logic to it.

    Chapter 4, Transactions and Concurrency Control, covers ACID transactions and optimistic concurrency control.

    Chapter 5, Querying, covers the many querying options available to Entity Framework Core, some of which are quite new.

    Chapter 6, Advanced Scenarios, presents some more advanced scenarios.

    Chapter 7, Performance and Scalability, introduces you to some tips related to how we can make our application more responsive and scalable.

    Appendix, Pitfalls, presents a list of pitfalls, or anti-patterns, regarding Entity Framework Core usage.

    What you need for this book

    All you need is .NET Core, including Entity Framework Core, together with an edition of Visual Studio 2015 that supports it (the free Community Edition will work).

    We will be using SQL Server as the relational database (any version starting with 2012 will do, in any edition), including Express.

    Who this book is for

    This book is for .NET developers who work with relational databases on a daily basis and understand the basics of Entity Framework, but now want to use it in a more efficient manner. You are expected to have some prior knowledge of Entity Framework.

    Sections

    In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

    To give clear instructions on how to complete a recipe, we use these sections as follows:

    Getting ready

    This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

    How to do it…

    This section contains the steps required to follow the recipe.

    How it works…

    This section usually consists of a detailed explanation of what happened in the previous section.

    There's more…

    This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

    See also

    This section provides helpful links to other useful information for the recipe.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Create an entity with the name MyEntity in the BusinessLogic project.

    A block of code is set as follows:

    namespace BusinessLogic

    {

      public class Post : BlogContent

      {

        public string Body { get; set; }

      }

    }

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    namespace BusinessLogic

    {

      public class Post : BlogContent

      {

       

    public string Body { get; set; }

     

      }

    }

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Open Using EF Core Solution from the included source code examples.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Entity-Framework-Core-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at <[email protected]> with a link to the suspected pirated material.

    We appreciate your help in protecting our authors and our ability to bring you valuable content.

    Questions

    If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

    Chapter 1. Improving Entity Framework in the Real World

    In this chapter, we will cover the following topics:

    Improving Entity Framework by using a code-first approach

    Unit testing and mocking

    Creating databases from code

    Creating mock database connections

    Implementing the repository pattern

    Implementing the unit of work pattern

    Introduction

    If we were to buy the materials to build a house, would we buy the bare minimum to get four walls up and a roof, without a kitchen or a bathroom? Or would we buy enough material to build the house with multiple bedrooms, a kitchen, and multiple bathrooms?

    The problem lies in how we define the bare minimum. The progression of software development has made us realize that there are ways of building software that do not require additional effort, but reap serious rewards. This is the same choice we are faced with when we decide on the approach to take with Entity Framework. We could just get it running and it would work most of the time.

    Customizing and adding to it later would be difficult, but doable. There are a few things that we would need to give up for this approach. The most important among those is control over how the code is written. We have already seen that applications grow, mature, and have features added. The only thing that stays constant is the fact that at some point in time, in some way, we will come to push the envelope of almost every tool that we leverage to help us. The other side is that we could go into development, being aware of the value-added benefits that cost nothing, and with that knowledge, avoid dealing with unnecessary constraints.

    When working with Entity Framework, there are some paths and options available to us. There are two main workflows for working with Object-Relational Mapper (ORM) tools such as Entity Framework:

    Database first: We start by defining our database objects and their relations, then write our classes to match them, and we bind them together

    Code first: We start by designing our classes as Plain Old CLR Objects (POCOs) to model the concepts that we wish to represent, without caring (too much!) how they will be persisted in the database

    Note

    The model-first approach was dropped in Entity Framework Core 1.0.

    While following the database-first approach, we are not concerned with the actual implementation of our classes, but merely the structures—tables, columns, keys—on which they will be persisted. In contrast, with POCOs or code first, we start by designing the classes that will be used in our programs to represent the business and domain concepts that we wish to model. This is known as Domain-Driven Design (DDD). DDD certainly includes code first, but it is much more than that.

    All of these approaches will solve the problem with

    Enjoying the preview?
    Page 1 of 1