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 now! 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
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

Arrow left icon
Profile Icon Prabhakaran Anbazhagan
Arrow right icon
$29.99 $43.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
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Prabhakaran Anbazhagan
Arrow right icon
$29.99 $43.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
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.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

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

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
$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 $ 183.97
Learning ASP.NET Core 2.0
$48.99
Mastering Entity Framework Core 2.0
$54.99
C# 7.1 and .NET Core 2.0 ??? Modern Cross-Platform Development
$79.99
Total $ 183.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

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.