You are on page 1of 16

18/10/2019 CRUD Operation In ASP.

NET Core MVC Using Visual Studio Code

C# Corner Q3, 20
CRUD Operation In ASP.NET Core Become
MVC C#aUsing
member Visual
Corner Login
Studio Code Contribute Ask Question
Ankit Sharma Sep 10 2017 62.2k 10 12

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 Windows System.

Download Free .NET & JAVA Files API


Try Free File Format APIs for Word/Excel/PDF

MvcDemo.rar

Introduction

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
Records Management System.

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

Prerequisites

Install .NET Core 2.0.0 SDK from here.


Download and install Visual Studio Code from here.
Familiarize yourself with Visual Studio Code from here.

Now, we are ready to proceed with creation of our rst web app. 

Create the MVC Web App

Press Window+R. It will open the "Run" window. Type ‘cmd’ and press ‘OK’. It will open the
command prompt in your system.

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 1/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

C# Corner Q3, 20

Become
C#aCorner
member Login

Contribute Ask Question

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

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 2/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

C# Corner Q3, 20

Become
C#aCorner
member Login

Contribute Ask Question

Add data Model Class

Right click on Models folder and select a "New " le. Give it a name such as Employees.cs. It will
create a le inside Models folder.

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 3/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

C# Corner Q3, 20

Become
C#aCorner
member Login

Contribute Ask Question

Open Employees.cs le and paste the following code to create Employee class.

01. using System;


02. using System.ComponentModel.DataAnnotations;
03.
04. namespace MvcDemo.Models
05. {
06. public class Employees
07. {
08. public int Id { get; set; }
09. [Required]
10. public string Name { get; set; }
11. [Required]
12. public string City { get; set; }
13. [Required]
14. public string Department { get; set; }
15. [Required]
16. public int Salary {get;set;}
17. }
18. }

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 4/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

Since we are adding


C#the required
Corner Q3, 20 validators to the elds of Employee class, so we need using
System.ComponentModel.DataAnnotations at the top. Become
C#aCorner
member Login

Add references for sca olding Contribute Ask Question

Now, our data model class is created. We will create Views and Controllers using sca olding. For
sca olding, we need to add NuGet package references in <ItemGroup> tag in MvcDemo.csproj
le.

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


02.
03. <PropertyGroup>
04. <TargetFramework>netcoreapp2.0</TargetFramework>
05. </PropertyGroup>
06.
07. <ItemGroup>
08. <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
09. <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Des
10. </ItemGroup>
11.
12. <ItemGroup>
13. <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGenerati
14. <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.Dot
15. </ItemGroup>
16.
17. </Project>

Save the le 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 MVCEmployeeContext.cs le in our Models folder. Open the le and add
the following lines of code.

01. using Microsoft.EntityFrameworkCore;


02.
03. namespace MvcDemo.Models
https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 5/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

04. { C# Corner Q3, 20


05. public class MvcEmployeeContext : DbContext
06. { BecomeC#aCorner
member Login
07. public MvcEmployeeContext (DbContextOptions<MvcEmployeeContext> opti
08. : base(options) Contribute Ask Question
09. {
10. }
11.
12. public DbSet<MvcDemo.Models.Employees> Employee { get; set; }
13. }
14. }

Now, your MVCEmployeeContext.cs le looks like this.

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

01. using Microsoft.EntityFrameworkCore;


02. using MvcDemo.Models

Add database context to Startup.cs le by adding following line in Con gureServices method

01. 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 de ning one entity set of Employee object, which will be represented in the database as an
Employee table.

So our Startup.cs willl look like this,

01. using System;


02. using System.Collections.Generic;
03. using System.Linq;
04. using System.Threading.Tasks;
05. using Microsoft.AspNetCore.Builder;
https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 6/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

06. using Microsoft.AspNetCore.Hosting;


C# Corner Q3, 20
07. using Microsoft.Extensions.Configuration;
08. using Microsoft.Extensions.DependencyInjection; Become
C#aCorner
member Login
09. using Microsoft.EntityFrameworkCore;
10. using MvcDemo.Models; Contribute Ask Question
11.
12. namespace MvcDemo
13. {
14. public class Startup
15. {
16. public Startup(IConfiguration configuration)
17. {
18. Configuration = configuration;
19. }
20.
21. public IConfiguration Configuration { get; }
22. public void ConfigureServices(IServiceCollection services)
23. {
24. services.AddMvc();
25.
26. services.AddDbContext<MvcEmployeeContext>
(options =>options.UseSqlite("Data Source=MvcEmployee.db"));
27. }
28.
29. // This method gets called by the runtime. Use this method to config
30. public void Configure(IApplicationBuilder app, IHostingEnvironment e
31. {
32. if (env.IsDevelopment())
33. {
34. app.UseDeveloperExceptionPage();
35. }
36. else
37. {
38. app.UseExceptionHandler("/Home/Error");
39. }
40.
41. app.UseStaticFiles();
42.
43. app.UseMvc(routes =>
44. {
45. routes.MapRoute(
46. name: "default",
47. template: "{controller=Home}/{action=Index}/{id?}");
48. });
49. }
50. }
51. }

Sca old the Employee Controller

Now, we are going to Sca old the controller and Razor view les. Navigate to MvcDemo project
folder in your system.

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 7/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

Press and hold Shift


C#and right
Corner Q3,click,
20 it will give you the option to “open PowerShell window here
“as shown in image below. Click and it will open a PowerShell window.
Become a member Login
C# Corner
Contribute Ask Question

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

Run the following commands in PowerShell console.

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

This will create following in our project

An Employee controller (Controllers/EmployeeController.cs)

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 8/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

Razor view les Q3, 20Delete, Details, Edit and Index pages (Views/Employee/\.cshtml)
for Create,
C# Corner

Become
C#aCorner
member Login

Contribute Ask Question


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

Initial Migration of Database

Open PowerShell in Project folder again.

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 speci ed in the DbContext (In the
Models/MVCEmployeeContext.cs le).

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

And that’s it. We have created our rst ASP.Net Core MVC application.

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 9/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

Before running theC#application ,open launch.json and make sure that ‘Program’ path is set
Corner Q3, 20
correctly as Become a member Login C# Corner
01. "program": "${workspaceRoot}/bin/Debug/netcoreapp2.0/MvcDemo.dll"
Contribute Ask Question

 Now your launch.json will look like this,

01. {
02. // Use IntelliSense to find out which attributes exist for C# debugging
03. // Use hover for the description of the existing attributes
04. // For further information visit https://github.com/OmniSharp/omnisharp-
vscode/blob/master/debugger-launchjson.md
05. "version": "0.2.0",
06. "configurations": [
07. {
08. "name": ".NET Core Launch (web)",
09. "type": "coreclr",
10. "request": "launch",
11. "preLaunchTask": "build",
12. // If you have changed target frameworks, make sure to update th
13. "program": "${workspaceRoot}/bin/Debug/netcoreapp2.0/MvcDemo.dll
14. "args": [],
15. "cwd": "${workspaceRoot}",
16. "stopAtEntry": false,
17. "internalConsoleOptions": "openOnSessionStart",
18. "launchBrowser": {
19. "enabled": true,
20. "args": "${auto-detect-url}",
21. "windows": {
22. "command": "cmd.exe",
23. "args": "/C start ${auto-detect-url}"
24. },
25. "osx": {
26. "command": "open"
27. },
28. "linux": {
29. "command": "xdg-open"
30. }
31. },
32. "env": {
33. "ASPNETCORE_ENVIRONMENT": "Development"
34. },
35. "sourceFileMap": {
36. "/Views": "${workspaceRoot}/Views"
37. }
38. },
39. {
40. "name": ".NET Core Attach",
41. "type": "coreclr",
42. "request": "attach",
43. "processId": "${command:pickProcess}"
44. }
45. ]
46. }
https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 10/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

C# Corner Q3, 20
Now press F5 to debug the application. It will open the browser, navigate
Become toa member Login
C# Corner
http://localhost:xxxx/employee
Contribute Ask Question
You can see the page shown below.

 
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
image below.
If we miss data in any elds while creating employee record, we will get a required eld validation
message.
After you click on Create button in "Create View", it will redirect to Index View where we can see
all the employees added by us. Here, we can also see action methods Edit, Details and Delete.

If we want to edit an existing employee record, then click Edit action link. It will open Edit View as
below where we can change the employee data. 

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

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

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

Click on Back to List to go back to Index view.Now we will perform Delete operation on Employee
with name Dhiraj.Click on Delete action link which will open Delete view asking for a con rmation
to delete the employee.
Once we click on Delete button the employee record gets deleted and we will be redirected to
Index view. Here we can see that the employee with name Dhiraj has been removed from our
record.

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 11/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

An Insight into Delete method


C# Corner Q3, 20

Become aCorner
member Login
Open EmployeeController.cs and scroll down to Delete method. You canC#
observe that we have
two Delete method, one each for HTTP Get and HTTP Post. Contribute Ask Question

01. // GET: Employee/Delete/5


02. public async Task<IActionResult> Delete(int? id)
03. {
04. if (id == null)
05. {
06. return NotFound();
07. }
08.
09. var employees = await _context.Employee
10. .SingleOrDefaultAsync(m => m.Id == id);
11. if (employees == null)
12. {
13. return NotFound();
14. }
15.
16. return View(employees);
17. }
18.
19. // POST: Employee/Delete/5
20. [HttpPost, ActionName("Delete")]
21. [ValidateAntiForgeryToken]
22. public async Task<IActionResult> DeleteConfirmed(int id)
23. {
24. var employees = await _context.Employee.SingleOrDefaultAsync(m =>
25. _context.Employee.Remove(employees);
26. await _context.SaveChangesAsync();
27. return RedirectToAction(nameof(Index));
28. }

Note that the HTTP GET Delete method doesn't delete the speci ed 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 DeleteCon rmed 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 perform
CRUD operations on it. We have used Entity Framework and SQLite for our Demo. Please refer to
attached code for better understanding.

See Also

CRUD Operations With ASP.NET Core Using Angular 5 And ADO.NET


https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 12/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

ASP.NET CoreC#- CRUD


Corner Using
Q3, 20 Angular 5 And Entity Framework Core
CRUD Operation With ASP.NET Core MVC Web App Using ADO.NET
BecomeC#aCorner
member Login
CRUD Operation With ASP.NET Core MVC Using Visual Studio Code And ADO.NET
Contribute Ask Question
Reference

https://docs.microsoft.com/en-us/aspnet/core/tutorials/ rst-mvc-app-xplat/

Next Recommended Article


CRUD Operation With ASP.NET Core MVC Using Visual Studio Code And ADO.NET

In this article we are going to create a web application using ASP Core MVC with the help of
Visual Studio Code and ADO.NET.

ASP.NET Core MVC Core

Ankit Sharma

C# Corner MVP | Dzone MVB | Author | Speaker | Senior Software Engineer | Passionate
Programmer | Medium: https://medium.com/@ankitsharmablog
https://ankitsharmablogs.com/

123 1.7m 2

12 10

Type your comment here and press Enter Key (Minimum 10 characters)

Is there any article crud using ado.net in asp.net core in linux platform?
Santosh Pattar Apr 04, 2019
1677 172 0 0 0 Reply

This is a great article. Can you continue update article that show how to add new Property to
Employee. Many thanks.
Minh Toan Jun 20, 2018
1831 18 0 0 0 Reply

Great Article , Please can you share with us REACT + ASP.net CORE 2.0 CRUD operation ?
SUJIL KUMAR Apr 18, 2018
1753 96 917 0 2 Reply

Thanks for reading my article. I will try to write on this.


Ankit Sharma Apr 18, 2018
123 15.3k 1.7m 0

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 13/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

Here you goQ3,


C# Corner https://www.c-sharpcorner.com/article/asp-net-core-crud-with-reactjs-and-
20
entity-framework-core/
Ankit Sharma
Become
C#aCorner
member Login
Apr 25, 2018
123 15.3k 1.7m 0
Contribute Ask Question
Nice..................................
Dharmraj Thakur Nov 15, 2017
275 7k 253.1k 0 0 Reply

Hi good job. One small thing, in the command: “dotnet aspnet-codegenerator controller -name
EmployeeController -m Employees -dc MvcEmployeeContext --relativeFolderPath Controllers --
useDefaultLayout –referenceScriptLibraries” before referenceScriptLibraries should be double dash
or short -script.
Sebastian Urbaniak Oct 21, 2017
1843 6 0 0 1 Reply

It will be double dash. It was a typo from my end. I have updated the article. Thanks for
pointing it out.
Ankit Sharma Oct 25, 2017
123 15.3k 1.7m 0

Great !!!!!!!!! way to go !!!!


Sundaram Subramanian Sep 21, 2017
102 18.4k 387.5k 1 1 Reply

Thanks Sundar.....
Ankit Sharma Sep 21, 2017
123 15.3k 1.7m 0

FEATURED ARTICLES

Processing Data With Azure Stream Analytics

Azure Blockchain Series - Part One

Easy Way To Become An F# Programmer For C# Developers


View All

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 14/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

C# Corner Q3, 20

Become
C#aCorner
member Login

Contribute Ask Question

TRENDING UP

01 Learn Angular 8 Step By Step in 10 Days – Pipes (Day 5)

02 Learn Angular 8 Step By Step in 10 Days – View Encapsulation (Day 6)

03 MS Team - Sync SharePoint Files With One Drive

04 Reusing A Deleted SharePoint Online Team Site Name

05 Overview Of SharePoint Column Indexing

06 Connect Your Virtual Machine Using Bastion

07 Establishing VPN Gateway Connection Between VNet To VNet

08 Building A Cross Platform MVVM Pattern With ReactiveUI And Xamarin.Forms

09 useRef() And Custom Hook In ReactJS

useMemo() Hook In ReactJS


https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 15/16
18/10/2019 CRUD Operation In ASP.NET Core MVC Using Visual Studio Code

10 C# Corner Q3, 20

Become member ViewLogin


C#aCorner All

Contribute Ask Question

About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ Partners

C# Tutorials Common Interview Questions Stories Consultants Ideas


©2019 C# Corner. All contents are copyright of their authors.

https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-mvc-using-visual-studio-code/ 16/16

You might also like