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
Note
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
.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).
Open Visual Studio and create a new project either from the File
menu or from the Start
page.
From the New Project
section, create a new project using any one of the following approaches:
- Select
Create new project...
. On the left pane, selectTemplates
|Visual C#
|.NET
C
ore
. Select theASP.NET Core Web Application template from the list.
- Search the project templates for the
ASP.NET Core Web Application
and select it. As displayed in the following screenshot, enterMasteringEFCore.Web
as theName
andMasteringEFCore
as theSolution name
and clickOK
:

New project
From the File menu, perform the following steps:
- Select
|New
.Project
- On the left pane, select
|Templates |
Visual C#
..NET Core
- Select the
ASP.NET Core Web Application template from the list.
- As displayed in the previous screenshot, enter
MasteringEFCore.CodeFirst.Starter
as theName
andMasteringEFCore
as theSolution name
and clickOK
.
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 projectWeb 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
- In our case, select
.NET Core
,ASP.NET Core 2.0
, and theWeb Application (Model-View-Controller)
template, and also keep the Authentication set toNo Authentication
. ClickOK
:
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.
Note
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.
A .NET Core web application is composed of the following folders:
Dependencies
: SDK, server, and client-side dependencieswwwroot
: All static resources should reside hereConnected Services
: To connect external services available in MarketplacelaunchSettings.json
: Settings required to launch a web applicationappSettings.json
: Configurations such as logging and connection stringsbower.json
: Client-side dependencies should be configured herebundleConfig.json
: Bundling is moved to the JSON configuration nowProgram.cs
: Everything starts fromMain()
and any program can be made into a web application using theWebHostBuilder
APIStartup.cs
: For adding and configuring startup services like MVC support, logging, static files support and so onControllers
,Views
: 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>© 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.
The Entity Framework package should be installed as part of the NuGet package, and can be done in the following ways:
- 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
- Go to the
Package Management
tab (either fromTools
or fromDependencies/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 fromSolution Explorer
and selectManage NuGet Packages for Solution...
- For project wise installation, right-click on
dependencies
from the desired project or right-click on the desired project and selectManage NuGet Packages...
- For a solution-wide installation, and availability for all projects that are part of the solution, go to
- Search for
Microsoft.EntityFrameworkCore.SqlServer
, select the stable version2.0.0
and install the package. It contains all the dependent packages as well (key dependencies such asSystem.Data.SqlClient
andMicrosoft.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.
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.
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>
.
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.
Note
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.
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.
Note
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.
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(); }
Note
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.
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 Manage
r
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.
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:
- Right-click on the
Controllers
folder and selectAdd
|New Scaffolded Item
. - A dialog box will be shown to
Add MVC Dependencies
. - Select
Minimal Dependencies
from the dialog box. Visual Studio adds the NuGet packages required to scaffold the MVC Controller and includes theMicrosoft.EntityFrameworkCore.Design
and theMicrosoft.EntityFrameworkCore.SqlServer.Design
packages. It also includesScaffoldingReadme.txt
, which is not required. We could just delete it.
Note
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:
- Right-click on the
Controllers
folder and selectAdd
|New Scaffolded Item
- In the
Add Scaffold
dialog, selectMVC Controller with views, using Entity Framework
as follows:

- In the
Add Controller
dialog, select the appropriateModel
andData context class
(Blog
andBlogContext
in our case), along with theBlogsController
auto-generated controller name:
- Click
Add,
shown as follows:

Scaffolded items
- The scaffolded code includes the CRUD operation in the MVC
Controllers
andViews
. 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()); } ... }
- 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 theIndex()
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> ...
- 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 theBlogs
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
Note
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.
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.