Book Image

Mastering Entity Framework Core 2.0

By : Prabhakaran Anbazhagan
Book Image

Mastering Entity Framework Core 2.0

By: Prabhakaran Anbazhagan

Overview of 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.
Table of Contents (20 chapters)
Title Page
Credits
About the Author
About the Reviewers
www.PacktPub.com
Customer Feedback
Dedication
Preface
4
Building Relationships – Understanding Mapping

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.