Mastering Entity Framework Core 2.0

4.3 (3 reviews total)
By Prabhakaran Anbazhagan
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Kickstart - Introduction to Entity Framework Core

About this book

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.

Publication date:
December 2017
Publisher
Packt
Pages
361
ISBN
9781788294133

 

Chapter 1. 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

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
 

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# | .NETCore. 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 New | Project.
  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 Core, ASP.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.

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.

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
  • Controllers, 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>&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.

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.

 

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.

 

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();
    }

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.

 

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.

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:

  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 ControllersandViews. 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

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.

 

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.

About the Author

  • Prabhakaran Anbazhagan

    Prabhakaran Anbazhagan is a Microsoft Solution Architect living in Chennai, India. His passion for programming started while creating a website for his school, and that's where the never-ending journey started. He became the secretary of a technology group in college, creating websites yet again, automating symposiums, and much more.

    He started his career at a prestigious product-based company; his knowledge was respected and recognized by his seniors, who let him develop tools and automation to sharpen his talents. Lucky guy! People hardly ever get to nurture their talent, but he got a handful of opportunities to sharpen his skills and become a Solution Architect, becoming a jack of all trades but still an expert in .NET.

    Prabhakaran has more than 12 years of IT experience in architecting, designing, and developing mission-critical desktop, web, and mobile applications. He has experience in full-stack development spanning ASP.NET MVC, Web API, C#, Mobility expert in Swift, Objective-C, Blackberry Cascades, hybrid apps, SharePoint, JavaScript, jQuery, and MEAN.JS.

    Browse publications by this author

Latest Reviews

(3 reviews total)
thank you it was all good
good coverage of Entity framework Core.. for people loking at it for the first time
It has the information I need to increase my knowledge.

Recommended For You

C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development - Fourth Edition

Learn the fundamentals, practical applications, and latest features of C# 8.0 and .NET Core 3.0 from expert teacher Mark J. Price.

By Mark J. Price
Learn ASP.NET Core 3 - Second Edition

A beginner's guide to building fully functioning web applications from scratch using the latest features of ASP.NET Core 3 and C# 8

By Kenneth Yamikani Fukizi and 2 more
ASP.NET Core 3 and React

Build modern, scalable, and cloud-ready single-page applications using ASP.NET Core, React, TypeScript, and Azure

By Carl Rippon
Hands-On Design Patterns with C# and .NET Core

Apply design patterns to solve problems in software architecture and programming using C# 7.x and .NET Core 2

By Gaurav Aroraa and 1 more