DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Server-Side Pagination Using ASP.NET Core and Angular 8 - Part Three
  • Build a Simple Chat Server With gRPC in .Net Core
  • An Introduction to Type Safety in JavaScript With Prisma
  • Building a RESTful Service Using ASP.NET Core and dotConnect for PostgreSQL

Trending

  • Advancing Robot Vision and Control
  • A Guide to Auto-Tagging and Lineage Tracking With OpenMetadata
  • Agile’s Quarter-Century Crisis
  • The Future of Java and AI: Coding in 2025
  1. DZone
  2. Data Engineering
  3. Databases
  4. CRUD Operation With ASP.NET Core MVC Using Visual Studio Code and Entity

CRUD Operation With ASP.NET Core MVC Using Visual Studio Code and Entity

In this article, we take a look at how to create a simple web application using ASP.NET MVC and C#, and then how to use that app to perform CRUD operations.

By 
Ankit Sharma user avatar
Ankit Sharma
·
Dec. 14, 17 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
60.4K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, I am going to explain how to create a basic web application using ASP.NET Core MVC and Visual Studio Code in a Windows system. We are going to create a sample Employee database management system.

We will be using ASP.NET Core 2.0, the Entity Framework, and SQLite.

Prerequisites

  1. Install .Net Core 2.0.0 SDK from here.
  2. Download and install Visual Studio Code from here.
  3. Familiarize yourself with Visual Studio Code here.

Before proceeding further, I would recommend downloading the source code from GitHub.

Now we are ready to proceed and create our first web app.

Create the MVC Web App

Pressing Window+R  will open a Run window. Type 'cmd' and press 'OK.' It will open a command prompt in your system:

Type the following Commands. It will create our MVC application, "MvcDemo":

  • mkdir MvcDemo  
  • cd MvcDemo 
  • dotnet new mvc 

Open this "MvcDemo" application using Visual Studio code. If it prompts the message, "Required assets to build and debug are missing from 'MvcDemo'. Add them?" select yes.

Add a Data Model Class

Right click on Models folder and select New File. Give your file the name, Employees.cs. It will create a file insid the Model folder.

Open the Employees.cs file and paste the following code into it to create the Employees class:

using System;  
using System.ComponentModel.DataAnnotations;  

namespace MvcDemo.Models  
{  
    public class Employees  
    {  
        public int Id { get; set; }  
        [Required]  
        public string Name { get; set; }  
        [Required]  
        public string City { get; set; }  
        [Required]  
        public string Department { get; set; }  
        [Required]  
        public int Salary {get;set;}  
    }  
}

We are adding Required validators to the fields of the Employees class, so we need to use System.ComponentModel.DataAnnotations at the top.

Add References for Scaffolding

Now that our data model class is created, we will create Views and the Controller using scaffolding.

For scaffolding, we need to add NuGet package references in the MvcDemo.csproj file by adding the following code:

<Project Sdk="Microsoft.NET.Sdk.Web">  

  <PropertyGroup>  
    <TargetFramework>netcoreapp2.0</TargetFramework>  
  </PropertyGroup>  

  <ItemGroup>  
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />  
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" />  
  </ItemGroup>  

  <ItemGroup>  
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />  
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />  
  </ItemGroup>  

</Project>

Save the file and select "Restore" to the Info message, "There are unresolved dependencies."

Now your MvcDemo.csproj will look like this.

The next step is to add the MVCEmployeeContext.cs file into our Model folder. Open the file and add the following lines of code.

using Microsoft.EntityFrameworkCore;  

namespace MvcDemo.Models  
{  
    public class MvcEmployeeContext : DbContext  
    {  
        public MvcEmployeeContext (DbContextOptions<MvcEmployeeContext> options)  
            : base(options)  
        {  
        }  

        public DbSet<MvcDemo.Models.Employees> Employee { get; set; }  
    }  
}

Now your MVCEmployeeContext.cs file shoul look like this:

Now, open the Startup.cs file and add the following two using statements at the top:

using Microsoft.EntityFrameworkCore;  
using MvcDemo.Models

Add the database context to the Startup.cs file by adding the following line in the ConfigureServices method:

services.AddDbContext<MvcEmployeeContext>(options =>options.UseSqlite("Data Source=MvcEmployee.db"));

This line of code tells Entity Framework which model classes are included in the data model. You're defining one entity set of Employee objects, which will be represented in the database as an Employee table.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.Extensions.Configuration;  
using Microsoft.Extensions.DependencyInjection;  
using Microsoft.EntityFrameworkCore;  
using MvcDemo.Models;  

namespace MvcDemo  
{  
    public class Startup  
    {  
        public Startup(IConfiguration configuration)  
        {  
            Configuration = configuration;  
        }  

        public IConfiguration Configuration { get; }  
        public void ConfigureServices(IServiceCollection services)  
        {  
            services.AddMvc();  

            services.AddDbContext<MvcEmployeeContext>(options =>options.UseSqlite("Data Source=MvcEmployee.db"));  
        }  

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
        {  
            if (env.IsDevelopment())  
            {  
                app.UseDeveloperExceptionPage();  
            }  
            else  
            {  
                app.UseExceptionHandler("/Home/Error");  
            }  

            app.UseStaticFiles();  

            app.UseMvc(routes =>  
            {  
                routes.MapRoute(  
                    name: "default",  
                    template: "{controller=Home}/{action=Index}/{id?}");  
            });  
        }  
    }  
}

Scaffold the Employee Controller

Now we are going to scaffold the Controller and Razor view files. Navigate to the MvcDemo project folder in your system.

Press and hold Shift and right click. It will give you the option to "open PowerShell window here," as shown in the image below. Click and it will open a PowerShell window.

Here, I am using Windows PowerShell but you can use command prompt also. It will give the same results.

Run the following commands:

  • dotnet restore 
dotnet aspnet-codegenerator controller -name EmployeeController -m Employees -dc MvcEmployeeContext --relativeFolderPath Controllers --useDefaultLayout --referenceScriptLibraries

This will create the following in our project:

  • An Employee controller (Controllers/EmployeeController.cs)
  • Razor view files for Create, Delete, Details, Edit, and Index pages (Views/Employee/.cshtml)

This process of automatically creating CRUD (Create, Read, Update, Delete) action methods and views is known as scaffolding.

Initial Migration of the Database

Open PowerShell in the Project folder.

Run the following commands:

  • dotnet ef migrations add InitialCreate 
  • dotnet ef database update 

The dotnet ef migrations add InitialCreate command generates code to create the initial database schema. The schema is based on the model specified in the DbContext (in the Models/MVCEmployeeContext.cs file).

After running the second command you will get a message at end "Done."

And that's it. We have created our first ASP.NET Core MVC application.

Before running the application, open launch.json and make sure that 'Program' path is set correctly:

"program": "${workspaceRoot}/bin/Debug/netcoreapp2.0/MvcDemo.dll"

Now your launch.json will look like this:

{  
   // Use IntelliSense to find out which attributes exist for C# debugging  
   // Use hover for the description of the existing attributes  
   // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md  
   "version": "0.2.0",  
   "configurations": [  
        {  
            "name": ".NET Core Launch (web)",  
            "type": "coreclr",  
            "request": "launch",  
            "preLaunchTask": "build",  
            // If you have changed target frameworks, make sure to update the program path.  
            "program": "${workspaceRoot}/bin/Debug/netcoreapp2.0/MvcDemo.dll",  
            "args": [],  
            "cwd": "${workspaceRoot}",  
            "stopAtEntry": false,  
            "internalConsoleOptions": "openOnSessionStart",  
            "launchBrowser": {  
                "enabled": true,  
                "args": "${auto-detect-url}",  
                "windows": {  
                    "command": "cmd.exe",  
                    "args": "/C start ${auto-detect-url}"  
                },  
                "osx": {  
                    "command": "open"  
                },  
                "linux": {  
                    "command": "xdg-open"  
                }  
            },  
            "env": {  
                "ASPNETCORE_ENVIRONMENT": "Development"  
            },  
            "sourceFileMap": {  
                "/Views": "${workspaceRoot}/Views"  
            }  
        },  
        {  
            "name": ".NET Core Attach",  
            "type": "coreclr",  
            "request": "attach",  
            "processId": "${command:pickProcess}"  
        }  
    ]  
}

Now press F5 to debug the application. It will open the browser, navigate to http://localhost:xxxx/employee.

You can see the below page.

Now we will proceed with our CRUD operations.

Click on CreateNew to create a new Employee record. Add a new Employee record as shown in the image below.

If we miss data in any fields then we will get a required field validation message.

After You click on the Create button, in Create View it will redirect us to the Index view where we can see all the employees added by us. Here, we can also see the action methods Edit, Details, and Delete.

If we want to edit any existing employee records, then click the Edit action link. This will open the Edit view, as shown below, where we can change the employee data.

Here, we have changed the Salary of the employee with name Dhiraj from 200000 to 250000. Click on Save to return to the Index view and see the updated changes as highlighted in the image below.

If we miss any fields while editing employee records, then the edit view will also throw the required field validation error message.

If you want to see the details of any Employee, then click on the Details action link, which will open the Details view as shown in the image below.

Click on Back to List to go back to the Index view. Now, we will perform the Delete operation on the Employee with the name Dhiraj. Click on the Delete action link which will open the Delete view and ask for a confirmation to delete.

Once we click on the Delete button, the employee record gets deleted and we will be redirected to the Index view. Here, we can see that the employee with the name Dhiraj has been removed from our record.


An Insight Into the Delete Method

Open EmployeeController.cs and scroll down to the Delete method. You can observe that we have two Delete methods, one for both HTTP GET and HTTP POST.

// GET: Employee/Delete/5  
       public async Task<IActionResult> Delete(int? id)  
       {  
           if (id == null)  
           {  
               return NotFound();  
           }  

           var employees = await _context.Employee  
               .SingleOrDefaultAsync(m => m.Id == id);  
           if (employees == null)  
           {  
               return NotFound();  
           }  

           return View(employees);  
       }  

       // POST: Employee/Delete/5  
       [HttpPost, ActionName("Delete")]  
       [ValidateAntiForgeryToken]  
       public async Task<IActionResult> DeleteConfirmed(int id)  
       {  
           var employees = await _context.Employee.SingleOrDefaultAsync(m => m.Id == id);  
           _context.Employee.Remove(employees);  
           await _context.SaveChangesAsync();  
           return RedirectToAction(nameof(Index));  
       }

Note that the HTTP GET Delete method doesn't delete the specified employee record, it returns a view of the employee where you can submit (HttpPost) the deletion. Performing a delete operation in response to a GET request (or for that matter, performing an edit operation, create operation, or any other operation that changes data) opens up a security hole.

The [HttpPost] method that deletes the data is named DeleteConfirmed to give the HTTP POST method a unique signature.

Conclusion

We have learned about creating a sample web application using ASP.NET Core MVC and how to perform CRUD operations with it. We have used Entity Framework and SQLite for our Demo. Please post your valuable feedback in comments section.

Download the source code from GitHub.

ASP.NET Database Visual Studio Code ASP.NET Core code style Web application

Published at DZone with permission of Ankit Sharma, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Server-Side Pagination Using ASP.NET Core and Angular 8 - Part Three
  • Build a Simple Chat Server With gRPC in .Net Core
  • An Introduction to Type Safety in JavaScript With Prisma
  • Building a RESTful Service Using ASP.NET Core and dotConnect for PostgreSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!