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
Conferences
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

eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Switzerland

Standard delivery 10 - 13 business days

€11.95

Premium delivery 3 - 6 business days

€16.95
(Includes tracking information)

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 : 9781788294133
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Switzerland

Standard delivery 10 - 13 business days

€11.95

Premium delivery 3 - 6 business days

€16.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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 €5 each
Feature tick icon Exclusive print discounts
€264.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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 138.97
Learning ASP.NET Core 2.0
€36.99
Mastering Entity Framework Core 2.0
€41.99
C# 7.1 and .NET Core 2.0 ??? Modern Cross-Platform Development
€59.99
Total 138.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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela