41,99 €
Leverage the full potential of Entity Framework with this collection of powerful and easy-to-follow recipes
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.
Entity Framework is a highly recommended Object Relation Mapping tool used to build complex systems. In order to survive in this growing market, the knowledge of a framework that helps provide easy access to databases, that is, Entity Framework has become a necessity. This book will provide .NET developers with this knowledge and guide them through working efficiently with data using Entity Framework Core.
You will start off by learning how to efficiently use Entity Framework in practical situations. You will gain a deep understanding of mapping properties and find out how to handle validation in Entity Framework. The book will then explain how to work with transactions and stored procedures along with improving Entity Framework using query libraries. Moving on, you will learn to improve complex query scenarios and implement transaction and concurrency control. You will then be taught to improve and develop Entity Framework in complex business scenarios. With the concluding chapter on performance and scalability, this book will get you ready to use Entity Framework proficiently.
Filled with rich code-based examples, this book takes a recipe-based approach that will teach .NET developers to improve their understanding of Entity Framework and help them effortlessly apply this knowledge in everyday situations.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 312
Veröffentlichungsjahr: 2016
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
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
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."
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!
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 <[email protected]> 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.
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.
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.
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.
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.
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:
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.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
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:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
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.
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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.
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.
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:
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:
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!
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 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.
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.
In this chapter, we will cover the following topics:
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:
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 asDomain-Driven Design (DDD). DDD certainly includes code first, but it is much more than that.
All of these approaches will solve the problem with varying degrees of flexibility.
Starting with a database-first approach in Entity Framework means we have an existing database schema and are going to let the schema, along with the metadata in the database, determine the structure of our business objects and domain model. The database-first approach is normally how most of us start out with Entity Framework and other ORMs, but the tendency is to move toward more flexible solutions as we gain proficiency with the framework. This will drastically reduce the amount of code that we need to write, but will also limit us to working within the structure of the generated code. Entities, which are generated by default here, are not 100% usable with WCF services, ASP.NET Web APIs, and similar technologies – just think about lazy loading and disconnected entities, for example. This is not necessarily a bad thing if we have a well-built database schema and a domain model that translates well into Data Transfer Objects (DTOs). Such a domain and database combination is a rare exception in the world of code production. Due to the lack of flexibility and the restrictions on the way these objects are used, this solution is viewed as a short-term or small-project solution.
Modeling the domain first allows us to fully visualize the structure of the data in the application, and work in a more object-oriented manner while developing our application. Just think of this: a relational database does not understand OOP concepts such as inheritance, static members, and virtual methods, although, for sure, there are ways to simulate them in the relational world. The main reasons for the lack of adoption of this approach include the poor support for round-trip updates, and the lack of documentation on manipulating the POCO model so as to produce the proper database structure. It can be a bit daunting for developers with less experience, because they probably won't know how to get started. Historically, the database had to be created each time the POCO model changed, causing data loss when structural changes were made.
Coding the classes first allows us to work entirely in an object-oriented direction, and not worry about the structuring of the database, without the restrictions that the model-first designer imposes. This abstraction gives us the ability to craft a more logically sound application that focuses on the behavior of the application rather than the data generated by it. The objects that we produce that are capable of being serialized over any service have true persistence ignorance, and can be shared as contract objects as they are not specific to the database implementation. This approach is also much more flexible as it is entirely dependent on the code that we write. This allows us to translate our objects into database records without modifying the structure of our application. All of this, however, is somewhat theoretical, in the sense that we still need to worry about having primary key properties, generation strategies, and so on.
In each of the recipes presented in this book, we will follow an incremental approach, where we will start by adding the stuff we need for the most basic cases, and later on, as we make progress, we will refactor it to add more complex stuff.
