Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Mastering Entity Framework Core 2.0
Mastering Entity Framework Core 2.0

Mastering Entity Framework Core 2.0: Dive into entities, relationships, querying, performance optimization, and more, to learn efficient data-driven development

Arrow left icon
Profile Icon Prabhakaran Anbazhagan
Arrow right icon
AU$41.99 AU$60.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (5 Ratings)
eBook Dec 2017 386 pages 1st Edition
eBook
AU$41.99 AU$60.99
Paperback
AU$75.99
Subscription
Free Trial
Renews at AU$24.99p/m
Arrow left icon
Profile Icon Prabhakaran Anbazhagan
Arrow right icon
AU$41.99 AU$60.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (5 Ratings)
eBook Dec 2017 386 pages 1st Edition
eBook
AU$41.99 AU$60.99
Paperback
AU$75.99
Subscription
Free Trial
Renews at AU$24.99p/m
eBook
AU$41.99 AU$60.99
Paperback
AU$75.99
Subscription
Free Trial
Renews at AU$24.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Mastering Entity Framework Core 2.0

Preparing the database


We will use the same blogging system used in Chapter 1Kickstart - Introduction to Entity Framework Core. In this case, we will create SQL queries required for the existing database and then we will build our blogging system using the database-first approach. Let's write the SQL query of Blog and Post, which were required for the blogging system.

Blog entity script

We will create a Blog table, then alter it to add a primary key constraint, and finally, insert some dummy data into the table. The complete script is available in the GitHub repository at https://github.com/PacktPublishing/Mastering-Entity-Framework-Core/blob/master/Chapter%202/Final/MasteringEFCore.DatabaseFirst.Final/dbo.Blog.sql.

The script required for creating the Blog table and inserting the data is displayed as follows:

   // Code removed for brevity
    CREATE TABLE [dbo].[Blog] (
       [Id]  INT            IDENTITY (1, 1) NOT NULL,
       [Url] NVARCHAR (MAX) NULL
    );
    GO
    // Code removed...

Creating  new project


We have exhaustively seen how to create a new project in  Chapter 1Kickstart - Introduction to Entity Framework Core. Kindly refer to the steps involved in creating the project and use the following project information:

Project name: MasteringEFCore.DatabaseFirst

Solution name: MasteringEFCore

Installing Entity Framework

The Entity Framework package inclusion and the steps involved were also discussed extensively in Chapter 1, Kickstart - Introduction to Entity Framework Core. So let's focus on the packages that are required for the reverse engineering (database-first approach). The basic package required for the Entity Framework to integrate with SQL Server is as follows:

Add the following command in the PM Console to install the following package:

    Install-Package Microsoft.EntityFrameworkCore.SqlServer

We could also search and install the Microsoft.EntityFrameworkCore.SqlServer package using NuGet Package Manager window:

Microsoft.EntityFrameworkCore.SqlServer NuGet...

Reverse engineering the database


Reverse engineering can be performed on the NuGet Package Manager console. We have already seen how to open it, so just execute the following command to scaffold the context and models files:

    Scaffold-DbContext "Server 
   (localdb)\mssqllocaldb;Database=MasteringEFCoreDbFirst;
    Trusted_Connection=True;" 
      Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Note

Sometimes we might get errors stating that The package could not be located. The workaround would be opening the project in a separate solution. If we get an Unable to open the database error, then providing access in the SQL Management Studio (connecting the locals from the studio) would resolve the issue. SQL Server Management Studio (SSMS) is a free version and can be downloaded from https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms.

Please refer to the following screenshot:

The scaffolding process generates database context files and corresponding...

Registering context in services (.NET Core DI)


The warning displayed in the OnConfiguring(DbContextOptionsBuilder optionsBuilder) method needs to be addressed. So let's remove that method (highlighted in the following code) and perform configuration inside the Startup.cs file using dependency injection.

Refactoring the OnConfiguring() method

If we recap on how we have configured the database context, the auto-generated code had a hardcoded connection string used for configuration. To avoid it, we should have a mechanism to pass on the database context options to the DbContext base class; let's see how to do it:

    public partial class MasteringEFCoreDbFirstContext : DbContext
    {
      public virtual DbSet<Blog> Blog { get; set; }
      public virtual DbSet<Post> Post { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder
       optionsBuilder)
      {
        // Move this connection string to config file later
        optionsBuilder.UseSqlServer(@"Server...

Performing CRUD operations


We have already seen how to create CRUD operations right from scaffolding controllers to their corresponding views for the Blog model, so we will create them for the Post model in this section:

  1. Right-click on the Controllers folder and select Add | New Scaffolded Item.
  2.  Add Scaffold dialog box, select MVC Controller with views, using Entity Framework:

  1. In the Add Controller dialog box, select the appropriate Model class and Data Context class (Post and MasteringEFCoreDbFirstContext in our case) along with the auto-generated controller name, PostsController:

  1. Next click Add as shown in the following screenshot:

Scaffolded items

Note

The Blog URL should be displayed instead of the Blog ID, which was part of the scaffolding. As displaying the ID raises security issues and usability concerns, let's change this mapping to URL.

Let's start our changes from the Index.cshml file, where we have listed Blog.Id instead of Blog.Url

    @foreach (var item in Model) {
      <tr&gt...

Summary


We have learned how to leverage Entity Framework on an existing system that has a live database (for illustrative purposes, we have created SQL scripts to create and simulate an existing database). We have explored NuGet packages that expose the APIs required to reverse engineer the database (including database context and corresponding data models). Finally, we have consumed the existing database in our MVC application using the scaffolding tool (which was installed on the way), and have also seen the changes required to the auto-generated code (which were not covered in Chapter 1Kickstart - Introduction to Entity Framework Core). The database-first approach was just a mechanism used for building existing systems (leveraging EF in the existing system). So far, we have used relationships (new or existing ones), but haven't figured out the relationships supported by Entity Framework. Let's explore them in Chapter 3, Relationships – Terminology and Conventions.

Summary

We have learned how to leverage Entity Framework on an existing system that has a live database (for illustrative purposes, we have created SQL scripts to create and simulate an existing database). We have explored NuGet packages that expose the APIs required to reverse engineer the database (including database context and corresponding data models). Finally, we have consumed the existing database in our MVC application using the scaffolding tool (which was installed on the way), and have also seen the changes required to the auto-generated code (which were not covered in Chapter 1Kickstart - Introduction to Entity Framework Core). The database-first approach was just a mechanism used for building existing systems (leveraging EF in the existing system). So far, we have used relationships (new or existing...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Learn how to effectively manage your database to make it more productive and maintainable.
  • • Write simplified queries using LINQ to acquire the desired data easily
  • • Raise the abstraction level from data to objects so teams can function independently, resulting in easily maintainable code

Description

Being able to create and maintain data-oriented applications has become crucial in modern programming. This is why Microsoft came up with Entity Framework so architects can optimize storage requirements while also writing efficient and maintainable application code. This book is a comprehensive guide that will show how to utilize the power of the Entity Framework to build efficient .NET Core applications. It not only teaches all the fundamentals of Entity Framework Core but also demonstrates how to use it practically so you can implement it in your software development. The book is divided into three modules. The first module focuses on building entities and relationships. Here you will also learn about different mapping techniques, which will help you choose the one best suited to your application design. Once you have understood the fundamentals of the Entity Framework, you will move on to learn about validation and querying in the second module. It will also teach you how to execute raw SQL queries and extend the Entity Framework to leverage Query Objects using the Query Object Pattern. The final module of the book focuses on performance optimization and managing the security of your application. You will learn to implement failsafe mechanisms using concurrency tokens. The book also explores row-level security and multitenant databases in detail. By the end of the book, you will be proficient in implementing Entity Framework on your .NET Core applications.

Who is this book for?

This book is for .NET Core developers who would like to integrate EF Core in their application. Prior knowledge of .NET Core and C# is assumed.

What you will learn

  • • Create databases and perform CRUD operations on them
  • • Understand and build relationships (related to entities, keys, and properties)
  • • Understand in-built, custom, and remote validation (both client and server side)
  • • You will learn to handle concurrency to build responsive applications
  • • You will handle transactions and multi-tenancy while also improving performance

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 15, 2017
Length: 386 pages
Edition : 1st
Language : English
ISBN-13 : 9781788296212
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 15, 2017
Length: 386 pages
Edition : 1st
Language : English
ISBN-13 : 9781788296212
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
AU$24.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
AU$249.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just AU$5 each
Feature tick icon Exclusive print discounts
AU$349.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just AU$5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total AU$ 254.97
Learning ASP.NET Core 2.0
AU$67.99
Mastering Entity Framework Core 2.0
AU$75.99
C# 7.1 and .NET Core 2.0 ??? Modern Cross-Platform Development
AU$110.99
Total AU$ 254.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Kickstart - Introduction to Entity Framework Core Chevron down icon Chevron up icon
The Other Way Around – Database First Approach Chevron down icon Chevron up icon
Relationships – Terminology and Conventions Chevron down icon Chevron up icon
Building Relationships – Understanding Mapping Chevron down icon Chevron up icon
Know the Validation – Explore Inbuilt Validations Chevron down icon Chevron up icon
Save Yourself – Hack Proof Your Entities Chevron down icon Chevron up icon
Going Raw – Leveraging SQL Queries in LINQ Chevron down icon Chevron up icon
Query Is All We Need – Query Object Pattern Chevron down icon Chevron up icon
Fail Safe Mechanism – Transactions Chevron down icon Chevron up icon
Make It Real – Handling Concurrencies Chevron down icon Chevron up icon
Performance – It&#x27;s All About Execution Time Chevron down icon Chevron up icon
Isolation – Building a Multi-Tenant Database Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(5 Ratings)
5 star 60%
4 star 0%
3 star 20%
2 star 0%
1 star 20%
DocTRex Feb 09, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I'm honestly pretty disappointed. This book has multiple grammatical and technical errors. Certain methods with Pascal case names are referred to in camel case, < was printed in a code example by mistake, etc. I do think the book provides good information but it's rather dull, especially the word choice. It's very very repetitive. Not to mention half the book is completely unnecessary pictures which take up whole pages, bloating the page count. I think it's good information but all the books I've gotten from this publisher don't feel of quality.
Amazon Verified review Amazon
Alvin Ashcraft Dec 26, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was involved as a technical reviewer on three books this year. This title was the one that had the most familiar material to me going into the project. I have used Entity Framework in my professional work for a number of years now. Looking at the book through a more objective viewpoint, I think it would be great title to get developers up to speed quickly on Entity Framework Core, regardless of their previous experience with EF. Some experience or understanding of C# and .NET will be necessary. This isn't an intro to .NET programming.The book uses a familiar subject of a Blog as in the code samples, developing the blogging system as each chapter unfolds. Most developers will immediately grasp the business concepts behind the Blog. After introducing the framework, topics covered in the book include entity relationships, validation, security, LINQ queries, query objects, transactions, concurrency, and multi-tenancy.I would recommend this book to experienced developers of any level who are picking up Entity Framework Core, regardless of any previous experience with Entity Framework or other similar frameworks.
Amazon Verified review Amazon
ilavarasan Mar 23, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
While I find this book to be a good pathway for new comers to explore the Microsoft’s Entity Framework world, I would also recommend it as a reference guide for experienced .NET programmers as well. The author has traveled through every corners of the EF arena explaining them with easy to understand code examples right from creating DbContext, Data Entities, Creating and Consuming Models, Object Mapping, Fluent Api Validations, perform data operations via LINQ with concurrency handling etc. Some might find the examples, error messages very detailed or not required, but they help you walk through side-by-side as you encounter them during development.At first, I thought it would have been great if the book covered some more MVC/Web Api topics to have the entire Tech Stack of a typical system be covered, but given the scope of the book is with Entity Framework realized that was a bit too much of an ask. Something for the author to consider on his future books.Being that said, this book contains stuff for developers from almost all proficiency level. I would highly recommend this book!
Amazon Verified review Amazon
Christian Howell Apr 29, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
There were lots of wasted pages so it's hard to say how long it is.
Amazon Verified review Amazon
Gerald Howell Mar 23, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
The author of the book is obviously a programmer, but, there are a lot of omissions in the steps for writing the code, required references to core dependencies are left out or vaguely referred to, a few mistakes in the code also causes some issues when trying to follow the steps in the book to produce the desired effect. The response from the writer was "The naming convention was followed at the initial stage of the draft and later I reorganized the solution to adopt "Starter" and "Final” projects which might help the readers to catch up with the chapter. We could find starter projects available on each chapter, which would be the final content of the previous chapter which would help readers in fixing issues they might have faced in previous chapters to move on."Mind you I am only in Chapter One and have come across four major issues trying to follow along with the book. I appreciate that I can download the Writers' completed projects, which do not match the book examples in a lot of points, and see the functioning program, and see the references the author added to the program, so I can then go to my copy and make the desired changes so it will function. I could have done this without the book, well, that is an exaggeration, but having to keep loading the authors solutions just to see the proper implementation kind of defeats the reason for buying this book. Also, you may notice it is listed twice for me, because before I got the paperback delivered I paid for the Kindle version so I could get started. Waste of money to have done so. If you buy this book, only buy it in digital or paperback.I changed my rating after reading through chapters one through five of the book and looking at these other reviews, the examples do not work.The more I work through this book the more I hate it. There is way too much errata to even submit anymore. Do not waste your money.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.