Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
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
€28.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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

Kickstart - Introduction to Entity Framework Core

I still remember the days when we were spending quite a lot of time on working with relational databases rather than just focusing on solving business problems; those days are definitely gone. To elaborate, let's jot down the issues we had before ORM:

  • Data access layers were not portable, which made it hard to change from one platform to another.
  • There were no abstractions, which forced us to write manual mapping between objected-oriented objects and data entities.
  • Vendor-specific SQL statements, which requires knowledge to port between different RDBMS systems.
  • Relied heavily on triggers and stored procedures.

The entire product development process shifted towards tools and open source platforms, and even Microsoft took that path from .NET Core onward. If we keep spending time on writing code which could be achieved through tools, we might end up looking like cavemen.

The Entity Framework was created to address this concern; it was not introduced with the initial .NET framework but rather was introduced in .NET Framework 3.5 SP1.

If we look closely, it was obvious that the .NET team built it for the following reasons:

  • To minimize the time spent by the developers/architects on stuff like abstractions and the portable data access layer
  • So that the developers do not require vendor specific SQL knowledge
  • So that we can build object-oriented business logic by eradicating triggers and SPs
This book uses Visual Studio 2017 (the latest at the time of writing) and ASP.NET Core 2.0 MVC with Entity Framework 2.0. Even though Entity Framework 2.0 is the latest version, it is still an evolving one, so it would take time for the .NET team to develop all the existing features of Entity Framework 6.2 based on the full .NET Framework.

We will cover the following topics here:

  • Prerequisites
  • Creating a new project
  • Installing Entity Framework 2.0
  • Data models
  • Database context
  • Registering the context in services (.Net Core DI)
  • Creating and seeding databases
  • Performing CRUD operations

Prerequisites

.NET Core, the open source platform, paved the way for multi-platform support in Visual Studio 2017. The editors came in different flavors, supporting both platform-specific and cross-platform IDEs:

  • Visual Studio: An exclusive edition for Windows with Community, Professional and Enterprise editions:

Visual Studio 2017 IDE can be downloaded directly from https://www.visualstudio.com.

  • Visual Studio for Mac: An exclusive edition for macOS, which was actually inherited from Xamarin Studio (Xamarin was acquired by Microsoft):

Visual Studio for Mac can be downloaded from https://www.visualstudio.com/vs/visual-studio-mac/.

  • Visual Studio Code: The cross-platform editor from Microsoft for Windows, Linux, and macOS:

Download the desired version/edition of Visual Studio Code from https://www.visualstudio.com/downloads/.

The Visual Studio 2017 installer is segregated into workloads, individual components, and language packs. We will be installing and using Visual Studio Community 2017 with the workloads ASP.NET and web development and .NET Core cross-platform development. The workload is a combination of one or more individual components which can also be installed from the Individual components tab of the installer, as follows:

New Visual Studio installer with workloads 

We have looked at the different flavors/editions of Visual Studio available to us, and we will be using Visual Studio Community on our journey, which is free of charge for private and test purposes. It is up to the reader to pick an edition which suits their needs (the tools and scaffolding available in the IDE might differ).

Creating a new project

Open Visual Studio and create a new project either from the File menu or from the Start page.

The Start page

From the New Project section, create a new project using any one of the following approaches:

  1. Select Create new project.... On the left pane, select Templates | Visual C# | .NET Core. Select the ASP.NET Core Web Application template from the list.
  1. Search the project templates for the ASP.NET Core Web Application and select it. As displayed in the following screenshot, enter MasteringEFCore.Web as the Name and MasteringEFCore as  the Solution name and click OK:
New project

The File menu

From the File menu, perform the following steps:

  1. Select NewProject.
  2. On the left pane, select Templates | Visual C# | .NET Core.
  3. Select the ASP.NET Core Web Application template from the list.

 

  1. As displayed in the previous screenshot, enter MasteringEFCore.CodeFirst.Starter as the Name and MasteringEFCore as the Solution name and click OK.

Irrespective of the previous two approaches, the selected template will provide New ASP.NET Web Application (.NET Core) dialog, to let us choose from the following:

    • Empty
    • Web API: Creates a Web API project
    • Web Application (Model-View-Controller): Creates an MVC Web application which also allows us to create APIs

We will be selecting Web Application (Model-View-Controller) from the dialog as shown here:

New ASP.NET web project dialog
  1. In our case, select .NET CoreASP.NET Core 2.0, and the Web Application (Model-View-Controller) template, and also keep the Authentication set to No Authentication. Click OK:

ASP.NET Core web application

The generated web application displays a tabbed interface which is new to us (instead of displaying index.cshtml). It allows us to access documentation, connect to any service or even decide on publishing options right from the start page.

If we look closely, we will notice that Visual Studio was silently restoring the packages, and almost everything was part of a package in .NET Core. No more heavyweight framework which always loads tons of DLLs even though we don't require them! Now everything is broken into lighter packages which we could utilize based on our requirements.

I know getting into MVC would be a little outside of the scope of this chapter, but let's dig into a few details before we deep dive into the Entity Framework.

Structuring the web app

A .NET Core web application is composed of the following folders:

  • Dependencies: SDK, server, and client-side dependencies
  • wwwroot: All static resources should reside here
  • Connected Services: To connect external services available in Marketplace
  • launchSettings.json: Settings required to launch a web application
  • appSettings.json: Configurations such as logging and connection strings
  • bower.json: Client-side dependencies should be configured here
  • bundleConfig.json: Bundling is moved to the JSON configuration now
  • Program.cs: Everything starts from Main() and any program can be made into a web application using the WebHostBuilder API
  • Startup.cs: For adding and configuring startup services like MVC support, logging, static files support and so on
  • ControllersViews: Part of MVC and contains actions and corresponding views

The structure we had discussed so far is illustrated in the following screenshot:

ASP.NET Core Web Application structure

The following highlighted sections in Views\Shared\_Layout.cshtml should be modified with the desired application name:

    <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,
initial-scale=1.0" />
<
title>@ViewData["Title"] - MasteringEFCore.Web</title>
...
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
...
<a asp-area="" asp-controller="Home" asp-action="Index"
class="navbar-brand">MasteringEFCore.Web</a>
...
<div class="container body-content">
...
<footer>
<p>&copy; 2017 - MasteringEFCore.Web</p>
</footer>
...
</body>

We have created a .NET Core web application with no authentication and explored the structure of the project, which might help us understand MVC in .NET Core. If we expand the dependencies, it is evident that we don't have built-in support for Entity Framework (EF) Core. We will look at the different ways of identifying and installing the packages.

Installing Entity Framework

The Entity Framework package should be installed as part of the NuGet package, and can be done in the following ways:

  1. Go to the Package Manager Console (Tools | NuGet Package Manager | Package Manager Console), select the project where the package should be installed:

Add the following command in the PM Console to install the package on the selected project:

  Install-Package Microsoft.EntityFrameworkCore.SqlServer
The Package Manager Console will be opened as shown in the following screenshot, Kindly use this space to install the package using the preceding command:
PM console
  1. Go to the Package Management tab (either from Tools or from Dependencies/Project).
    • For a solution-wide installation, and availability for all projects that are part of the solution, go to Tools | NuGet Package Manager | Manage NuGet Packages for Solution... or right-click on the solution from Solution Explorer and select Manage NuGet Packages for Solution...
    • For project wise installation, right-click on dependencies from the desired project or right-click on the desired project and select Manage NuGet Packages...
  1. Search for Microsoft.EntityFrameworkCore.SqlServer, select the stable version 2.0.0 and install the package. It contains all the dependent packages as well (key dependencies such as System.Data.SqlClient and Microsoft.EntityFrameworkCore.Relational):
NuGet package manager window

We have looked at different ways of using the Package Manager console so far, and installed packages related to EF Core. In the next section, we will start building the schema and later consume the created entities using EF.

Data models

When we think about creating data models in the .NET world way before creating the database, we are a little bit off the legacy track, and yes, it's been widely called the Code-First approach. Let's create entity classes using code-first for the Blogging application, and put them into the Models folder under the project.

Blog entity

Create a Blog.cs class file and include the following properties:

    public class Blog
{
public int Id { get; set; }
public string Url { get; set; }
public ICollection<Post> Posts { get; set; }
}

The Entity Framework will look for any property with the name Id or TypeNameId and marks them as the primary key of the table. The Posts property is a navigation property which contains Post items related to this Blog entity. It doesn't matter whether we use ICollection<T> or IEnumerable<T> for the navigation property, EF will create a collection for us, HashSet<T> by default. We could also create a concrete collection using List<T>.

Post entity

Create a Post.cs class file and include the following properties:

    public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime PublishedDateTime { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}

The BlogId property is a foreign key created for the corresponding Blog navigation property. As you may notice in this case, we have an individual item as the navigation property, as opposed to a list in the Blog entity. This is where relationship type comes into the picture, which we will be exploring more in Chapter 3, Relationships – Terminology and Conventions.

EF will allow us to create an individual navigation property without any foreign key in the entity. In those cases, EF will create a foreign key for us in the database table using the BlogId pattern (the Blog navigation property along with its  Id primary key). EF will generate them automatically for all navigational properties against the Id primary key, but it also allows us to name it differently and decorate it via a custom attribute.

We have built the schema required for the application so far, but it was not configured in EF, so let's see how the data models get connected/configured with EF using database context.

Database context

The main entry point for EF would be any class that inherits the Microsoft.EntityFrameworkCore.DbContext class. Let's create a class called BlogContext and inherit the same. We will keep the context and other EF related configurations inside the Data folder. Create a Data folder in the project, and also create BlogContext.cs inside this folder:

    public class BlogContext: DbContext
{
public BlogContext(DbContextOptions<BlogContext> options)
: base(options)
{
}

public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}

EF interprets DbSet<T> as a database table; we have created a DbSet<T> property for all the entities for our blogging system. We usually name the properties in plural form as the property will hold list of entities, and EF will be using those property names while creating tables in the database.

Creating a DbSet for a parent entity is enough for EF to identify the dependent entities and create corresponding tables for us. EF will be using plural form while deciding table names.

.NET developers and SQL developers debate plural table names and often end up creating entities with two different conventions. As a framework, EF supports those scenarios as well. We could override the default plural naming behavior using Fluent API. Refer to the following Fluent API code:

    public class BlogContext: DbContext
{
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>().ToTable("Blog");
modelBuilder.Entity<Post>().ToTable("Post");
}
}

We have created a database context and configured the data models in it. You may notice we cannot see any connection string pointing to the database. It could have been done using the OnConfiguring() method with a hard-coded connection string, but it would not be an ideal implementation. Rather, we will use built-in dependency injection support from .NET Core to configure the same in the next section.

Registering the context in services (.NET Core DI)

The dependency injection support in the ASP.NET framework came too late for the .NET developers/architects who were seeking shelter from third-party tools such as Ninject, StructureMap, Castle Windsor, and so on. Finally, we gained support from ASP.NET Core. It has most of the features from the third-party DI providers, but the only difference is the configuration should happen inside the Startup.cs middleware.

First thing's first, let's configure the connection string in our new appSettings.json:

    "ConnectionStrings": {
"DefaultConnection": "Server
(localdb)\\mssqllocaldb;Database=MasteringEFCoreBlog;
Trusted_Connection=True;MultipleActiveResultSets=true"
},

Then configure the context as a service (all service configuration goes into Startup.cs). To support that, import MasteringEFCore.Web.Data and Microsoft.EntityFrameworkCore in the Startup class. Finally, add the DbContext to the services collection by creating and including DbContextOptionsBuilder using UseSqlServer():

    public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<BlogContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("
DefaultConnection"
)));
services.AddMvc();
}
We will be using a lightweight version of SQL Server called LocalDB for development. This edition was created with the intention of development, so we shouldn't be using it in any other environments. It runs with very minimal configuration, so it's invoked while running the application. The .mdf database file is stored locally. 

We have configured the database context using dependency injection, and at this stage, we are good to go. We are almost there. As of now, we have the schema required for the database and the context for EF and services being configured. All of these will end up providing an empty database with literally no values in it. Run the application and see that an empty database is created. It will be of no use. In the next section, let's see how we can seed the database with master data/create tables with sample data, which can be consumed by the application.

Creating and seeding databases

We have created an empty database, and we should have a mechanism by which we can seed the initial/master data that might be required by the web application. In our case, we don't have any master data, so all we can do is create a couple of blogs and corresponding posts. We need to ensure whether the database was created or not before we start adding data to it. The EnsureCreated method helps us in verifying this. Create a new DbInitializer.cs class file inside the Data folder and include the following code:

    public static void Initialize(BlogContext context)
{
context.Database.EnsureCreated();
// Look for any blogs.
if (context.Blogs.Any())
{
return; // DB has been seeded
}
var dotnetBlog = new Blog {
Url = "http://blogs.packtpub.com/dotnet" };
var dotnetCoreBlog = new Blog { Url =
"http://blogs.packtpub.com/dotnetcore" };
var blogs = new Blog[]
{
dotnetBlog,
dotnetCoreBlog
};
foreach (var blog in blogs)
{
context.Blogs.Add(blog);
}
context.SaveChanges();
var posts = new Post[]
{
new Post{Id= 1,Title="Dotnet 4.7 Released",Blog = dotnetBlog,
Content = "Dotnet 4.7 Released Contents", PublishedDateTime =
DateTime.Now},
new Post{Id= 1,Title=".NET Core 1.1 Released",Blog=
dotnetCoreBlog,
Content = ".NET Core 1.1 Released Contents", PublishedDateTime
=
DateTime.Now},
new Post{Id= 1,Title="EF Core 1.1 Released",Blog=
dotnetCoreBlog,
Content = "EF Core 1.1 Released Contents", PublishedDateTime =
DateTime.Now}
};
foreach (var post in posts)
{
context.Posts.Add(post);
}
context.SaveChanges();
}

In Program.cs, initialize DbInitializer in Main() by creating the BlogContext using dependency injection and pass the same to the DbInitializer.Initialize():

    public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<BlogContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred initializing
the database.");
}
}
host.Run();
}

One last piece of the puzzle is missing; we need to add migration whenever we add/manipulate data models, without which EF doesn't know how the database needs to be created/updated. The migration can be performed with the NuGet Package Manager console:

    Add-Migration InitialMigration

The preceding statement allows EF to create a migration file with tables created from the models configured in the DbContext. This can be done as follows:

    Update-Database

The preceding statement applies the migration created to the database. At this moment we are almost done with the EF configuration. We should run the application and verify the database regarding whether or not the proper schema and seed data were updated.

We could verify the table whether it contains seeded data using the following SQL Server Object Explorer:

Database created successfully

We can see that the schema was created properly inside the MSSQLLocalDB instance, and we should expand the tables and verify whether the seed data was updated or not. The seed data of the Blog entity was updated properly, which was verified with the following screenshot:

Blog table created with configured schema and seed data

The seed data of the Post entity was updated properly, which was verified with the following screenshot.

Post table created with configured schema and seed data

We have ensured that the database was created with the proper schema and seed data, and now we should start consuming the entities. In the next section, let's see how we can consume the entities in MVC using scaffolding rather than building everything on our own.

CRUD operations

Creating CRUD (Create/Read/Update/Delete) operations manually would take quite a long time. It's a repetitive operation that could be automated. The process of automating this CRUD operation is referred to as scaffolding:

  1. Right-click on the Controllers folder and select Add | New Scaffolded Item.
  2. A dialog box will be shown to Add MVC Dependencies.
  3. Select Minimal Dependencies from the dialog box.
    Visual Studio adds the NuGet packages required to scaffold the MVC Controller and includes the Microsoft.EntityFrameworkCore.Design and the Microsoft.EntityFrameworkCore.SqlServer.Design packages. It also includes ScaffoldingReadme.txt, which is not required. We could just delete it.
Once the minimal setup is completed, we need to build/rebuild the application otherwise the same Add MVC Dependencies dialog will be displayed instead of the Add Scaffold dialog.

At this point, the tools required to scaffold Controller and View are included by Visual Studio, and we are ready to start the process of scaffolding again:

  1. Right-click on the Controllers folder and select Add | New Scaffolded Item
  2. In the Add Scaffold dialog, select MVC Controller with views, using Entity Framework as follows:
  1. In the Add Controller dialog, select the appropriate Model and Data context class (Blog and BlogContext in our case), along with the BlogsController auto-generated controller name:
  1. Click Add, shown as follows:
Scaffolded items
  1. The scaffolded code includes the CRUD operation in the MVC Controllers and Views. Examining the scaffolded MVC code would be out of the scope of this chapter, so we will focus on the EF scaffolded part alone:
        public class BlogsController : Controller
{
private readonly BlogContext _context;
public BlogsController(BlogContext context)
{
_context = context;
}
// GET: Blogs
public async Task<IActionResult> Index()
{
return View(await _context.Blogs.ToListAsync());
}
...
}
  1. In the preceding code block, you may notice that the dependency injection was used when passing the BlogContext (MasteringEFCoreBlog database context) to the controller, which was also used in the Index() action:
        <div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-area="" asp-controller="Home"
asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Blogs"
asp-action="Index">Blogs</a></li
>
...
  1. We need to update the navigation, as displayed in the preceding code, in Views\Shared\_Layout.cshtml, without which we won't be able to view the CRUD operations in the Blogs module. All set. Let's run and see the CRUD operations in action:
     
Updated navigation menu with Blogs

The preceding screenshot is the home page of the ASP.NET Core web application. We have highlighted the Blogs hyperlink in the navigation menu. The Blogs hyperlink would take the user to the Index page, which would list all the blog items:

Blogs list

 Let's try to create a blog entry in the system, as follows:

Creating a Blog

The Create page provides input elements required to populate the entity which needs to be created, so let's provide the required data and verify it:

Blog detail page

The Details page displays the entity, and the preceding screenshot displays the entity that was just created. The Edit page provides input elements required and also pre-populates with existing data, which could be edited by using and updating the data:

Editing a Blog

The Delete page provides a confirmation view that lets the users confirm whether or not they would like to delete the item:

Deleting a Blog
This Delete page will be displayed when the user selects the Delete hyperlink in the item row on the list page. Instead of deleting the blog directly from the action, we will be routing the user to the Delete page to get confirmation before performing the action.

We have identified how to perform CRUD operations using EF Core; since exploring MVC was out of the scope of this book. We stuck to analyzing scaffolding related to EF only.

Summary

We started our journey with Entity Framework by knowing what difference it made when compared with the legacy approach at a high level. We also looked at building the .NET environment and creating and configuring the .NET Core web application with Entity Framework. We explored NuGet packages and package manager, which will be extensively used in the entire book. We also identified and installed the packages required for the Entity Framework in this chapter. Using the Code-First approach, we built the schema, configured them with EF and created and seeded the database with schema and seed data. Finally, we consumed the built schema in our MVC application using the scaffolding tool (which was installed along the way), and also looked at the usage of the database context in the controllers. The Code-First approach can be used for building new systems, but we need a different approach for existing systems. That's where the Database-First approach comes into the picture. Let's explore this in Chapter 2, The Other Way Around – Database First Approach.

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 copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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
$19.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
$199.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
$279.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
C# 7.1 and .NET Core 2.0 ??? Modern Cross-Platform Development
€59.99
Mastering Entity Framework Core 2.0
€41.99
Learning ASP.NET Core 2.0
€36.99
Total 138.97 Stars icon

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 digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

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