First CRUD Application In ASP.NET Core MVC Using Entity Framework Core


This article intends to explain basic Create, Read, Update and Delete (CRUD) operations in ASP.NET Core MVC using Entity Framework Core. We develop an application using Entity Framework “Code First” approach. To set up a development environment for ASP.NET Core MVC application, we follow steps which mentioned in the article Getting Started With ASP.NET Core MVC. The application uses a single entity named Book to perform CRUD operations and keep demonstration simple.

Create Database


The application uses Code First approach of the Entity Framework Core so add Entity Framework Core support into it. The application uses SQL Server database so it requires SQL Server database provider. This provider is available via NuGet package named Microsoft.EntityFrameworkCore.SqlServer. When an application creates then it includes Microsoft.AspNetCore.All NuGet metapackage. This package also includes Microsoft.EntityFrameworkCore.SqlServer, so we don’t have to install it.

Create the Data Model

The application performs CRUD operations on single entity but creates two entities which are BaseEntity and Book. The BaseEntity class has common properties and will be inherited by each other entities. The BaseEntity class creates as per following code snippet.

The application performs CRUD operations on an entity named Book. Now, create Book class that inherits from the BaseEntity class as per following code snippet.

Now, let’s define configuration for Book entity. Database table will be created using configuration of the Book entity. There is two option to define the configuration, one is Data Annotation and another is Fluent API. To follow SRP principle, we use second option Fluent API to define entity configuration. The following code snippet for BookMap class.

The EntityTypeBuilder supports Entity Framework Core infrastructure. The T represents that which entity being configured. It uses methods to define configuration for each field. Let’s see a couple of methods which used in preceding code.

  1. HasKey: It sets the entity properties that make up the primary key for it.
  2. Property: It returns an object that can be used to configure a property of entity type.

Now, we create context class named CRUDContext. It inherits from DbContext. It is a bridge between entity and database. It is a primary class that interacts with data as an object. We override OnModelCreating method in context class. When we use Fluent API then it defines that how the entities map to a database. The following is the code snippet for the context class named CRUDContext.cs.

Database Connectivity using EF

We defined a data model with context. Now, we define a connection between database and context. We have to follow following procedure to use context in the application.

1. We define a connection string to connect context to the database. Open the appsetting.json file and define connection string as per following code snippet.

It is similar to web.config file. It stores configuration level settings such as connection string, SMTP, Domain etc.

2. Application configuration initializes from Startup class. As this application is using the Entity Framework Core so we add two namespaces in the using. The following code snippet for same.

3. ASP.NET Core provides inbuilt Inversion of Control. Context registers to IoC during application start up. After that, context injects to MVC controller using constructor dependency injection. Hence, it registers as a service in Startup class. The following code snippet for ConfigureServices method where context registers as a service.

Database Initialize using EF Migration

We use the Entity Framework Core Migration to create a database from the data model. To perform the migration, we can use Package Manager Console (PMS) and Command Line Interface (CLI) either.

The Entity Framework Core tools for the CLI are provided in Microsoft.EntityFrameworkCore.Tool.DotNet. To install this package, we can’t use install-package command or package manager GUI. But we can install this package in the application to editing the .csproj file and add this package to the DotNetCliToolReference, The following XML code for same.

Now we need to follow steps to create a new database from a data model. These are

  1. Save Changes and build the project.
  2. Open solution location folder. In Solution Explorer, right-click the project and choose Open in File Explorer from the context menu.
  3. Write “cmd” command in the address bar and press Enter.

To initiate migration, enter the following command in the command window.

dotnet ef migrations add InitialCreate

Figure 1: Entity Framework Core Migration

Now, we apply the migration to the database. We enter following command in the command window. This commands creates database and tables in it.

dotnet ef database update

Hence, the database has been created using code first approach of Entity Framework Core.


Create Application User Interface

Now, we develop user interface for the application. First, we create view model named BookViewModel for application UI. This model strongly binds with a view. The following code snippet for the view model.

Now, create a controller named BookController under Controllers folder. This controller has action methods to perform CRUD operations. CRUDContext class instance injects into its constructor using dependency injection. The following code snippet for same.

Now, we develop the user interface for each CRUD operations. The views create for adding and editing a book, book listing and book deletion. Let’s see each view one by one.

Book Listing

It is the first view of the application. It shows all books in the listing. It displays book data in tabular format and has an option to add a new book. The book listing has options to edit and delete a book individually. It is an index view named index.cshtml under Book folder of Views. The following code snippet for same.

Now, let’s run the application. As a first request, it calls the index() action method with a HttpGet request and as a response all the books listed in the UI as in Figure 2.

Figure 2: Book Listing UI

Create / Edit Book View

As create and edit view are same so we create a common view for both. This view uses the same BookViewModel. Let’s define a create/edit book partial view. The following is the code snippet for _AddEditBook.cshtml.

The application performs data manipulation operation in the popup. It uses Bootstrap model popup. Once it opens in the browser, it saves as cache in the browser. To remove from cache and loading data, we create a javascript file as per following code snippet.

Let’s run the application, Click on either ‘Add Book’ button or ‘Edit’ button in the listing. It calls AddEditBook action method which sends partial view as a response. Figure 3 shows UI for add/edit a book.

Figure 3: Edit a Book UI

Delete a Book

Let’s perform last operation Delete. Each book data has a delete button in the listing. When a user clicks on delete button against a book then a popup shows to ask “Are you want to delete xxx?” as a confirmation. This delete popup holds two buttons one is Delete and another is Cancel. When a user clicks on Delete button of pop up then it makes a HttpPost request that calls the DeleteBook action method and deletes the book. The following is code snippet for _DeleteBook.cshtml

Let’s run the application and click on Delete button of listing. It shows UI in the model popup as in Figure 4 to delete a book.

Figure 4: Delete Confirmation for a Book


Conclusion

This article performed CRUD operations in ASP.NET Core using Entity Framework Core with code first development approach. Data manipulation operation performed in the model popup. The complete source code for this demonstration available at GitHub, click here to download.