In Focus

CRUD Operations In .NET Core 3.0 With Visual Studio 2019

In this article, we’ll learn how to perform CRUD operations with .NET Core 3.0 and Visual Studio 2019. We will use dapper to perform the CRUD operations.

Recommended Prerequisites

  • .NET Core 3.0 (Download from here)
  •  Visual Studio 2019. (Download from here)
Step 1 - Create a Database, Tables, and Stored Procedures.
 
First, we need to create a SQL Server database, tables, and stored procedure which we need to use in the application. 
 
Here, I'm creating a database, "CoreMaster" and a table "Job".
  1. CREATE TABLE [dbo].[Job](  
  2.     [JobID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [JobTitle] [nchar](250) NULL,  
  4.     [JobImage] [nvarchar](maxNULL,  
  5.     [CityId] [intNULL,  
  6.     [IsActive] [bitNULL,  
  7.     [CreatedBY] [nvarchar](50) NULL,  
  8.     [CreatedDateTime] [datetime] NULL,  
  9.     [UpdatedBY] [nvarchar](50) NULL,  
  10.     [UpdatedDateTime] [datetime] NULL,  
  11.  CONSTRAINT [PK_Job] PRIMARY KEY CLUSTERED   
  12. (  
  13.     [JobID] ASC  
  14. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  15. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
Now, I'm going to create stored procedures for adding job, fetching job list, and updating job.
 
The "Add Job" stored procedure is named "[SP_Add_Job]" which returns the inserted record's job Id.
  1. CREATE PROCEDURE [dbo].[SP_Add_Job]      
  2.     @JobTitle NVARCHAR(250) ,      
  3.     @JobImage NVARCHAR(Max) ,      
  4.     @CityId int ,      
  5.     @IsActive BIT ,      
  6.     @CreatedBY NVARCHAR(50) ,      
  7.     @CreatedDateTime DATETIME ,      
  8.     @UpdatedBY NVARCHAR(50),    
  9.     @UpdatedDateTime DATETIME    
  10.         
  11. AS      
  12.     BEGIN      
  13.  DECLARE @JobId as BIGINT    
  14.         INSERT  INTO [Job]      
  15.                 (JobTitle ,      
  16.                  JobImage ,      
  17.                  CityId ,      
  18.                  IsActive ,      
  19.                  CreatedBY ,      
  20.                  CreatedDateTime ,      
  21.                  UpdatedBY ,      
  22.                  UpdatedDateTime    
  23.              )      
  24.         VALUES  ( @JobTitle ,      
  25.                   @JobImage ,      
  26.                   @CityId ,      
  27.                   @IsActive ,      
  28.                   @CreatedBY ,        
  29.                   @CreatedDateTime ,     
  30.                   @UpdatedBY ,      
  31.                   @UpdatedDateTime                      
  32.                       
  33.              );     
  34.         SET @JobId = SCOPE_IDENTITY();     
  35.         SELECT  @JobId AS JobId;      
  36.     END;      
  37.     
  38.    
The "Update job" stored procedure is "[SP_Update_Job]".
  1. CREATE PROCEDURE [dbo].[SP_Update_Job]    
  2.     @JobId INT,  
  3.     @JobTitle NVARCHAR(250) ,        
  4.     @JobImage NVARCHAR(Max) ,        
  5.     @CityId INT ,        
  6.     @IsActive BIT ,    
  7.     @UpdatedBY NVARCHAR(50),      
  8.     @UpdatedDateTime DATETIME      
  9.           
  10. AS        
  11.     BEGIN        
  12.      UPDATE job   
  13.      SET    
  14.             job.JobTitle = @JobTitle,    
  15.             job.JobImage = @JobImage ,    
  16.             job.CityId = @CityId ,    
  17.             job.IsActive = @IsActive ,    
  18.             job.UpdatedBY = @UpdatedBY ,    
  19.             job.UpdatedDateTime = @UpdatedDateTime  
  20.   FROM [Job] job    
  21.   WHERE JobId = @JobId   
  22.     END;        
  23.       
The "Fetch job list" store procedure is [SP_Job_List].
  1. CREATE PROCEDURE [dbo].[SP_Job_List]      
  2. AS  
  3. BEGIN  
  4.       
  5.     SET NOCOUNT ON;  
  6.     select * from [Job]   
  7.     END  
Step 2 - Open Visual Studio 2019
 
Go to the Start menu on your Windows desktop and type Visual studio 2019; open it.
 
CRUD Operations In .NET Core 3.0 With Visual Studio 2019 
 
Step 3 - Create a new project
 
The Visual Studio 2019 welcome screen will pop up, which contains four boxes on the right side.
  1. Clone or checkout code
  2. Open a project or solution
  3. Open a local folder
  4. Create a new project
From the above options, we need to click on the "Create a new project" box. 
 
CRUD Operations In .NET Core 3.0 With Visual Studio 2019 
 
Click on the "ASP.NET Core Web Application" and press "Next".
 
CRUD Operations In .NET Core 3.0 With Visual Studio 2019 
 
From the wizard, select "Web Application (Model-View-Controller)". The framework must be selected as .NET Core 3.0. Then, click on the "OK" button.
 
CRUD Operations In .NET Core 3.0 With Visual Studio 2019 
 
Put an appropriate project name and select the location where you want to create this project. Again, click the "Create" button.
 
CRUD Operations In .NET Core 3.0 With Visual Studio 2019 
 
Now "Build" the project. It will install .NET Core 3.0 runtime (if it not installed on the machine).
 
Step 4 - Install NuGet packages.
 
We need to install the below packages.
  1. Microsoft.EntityFrameworkCore.SqlServer

    CRUD Operations In .NET Core 3.0 With Visual Studio 2019

  2. Microsoft.EntityFrameworkCore.SqlServer.Design

    CRUD Operations In .NET Core 3.0 With Visual Studio 2019

  3. Microsoft.EntityFrameworkCore.Tools

    CRUD Operations In .NET Core 3.0 With Visual Studio 2019

  4. Dapper

    CRUD Operations In .NET Core 3.0 With Visual Studio 2019
Step 5 - Create Dapper Class and Interface
 
Now, create two folders -
  1. Helper
  2. Interface 
In the Interface folder, add a new interface namely "IDapperHelper" and copy the below code and paste in that class.
  1. using Dapper;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data;  
  5. using System.Data.Common;  
  6. using System.Linq;  
  7. using System.Linq.Expressions;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace CoreDemo_3_0.Interfaces  
  11. {  
  12.     public interface IDapperHelper : IDisposable  
  13.     {  
  14.         DbConnection GetConnection();  
  15.         T Get<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure);  
  16.         List<T> GetAll<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure);  
  17.         int Execute(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure);  
  18.         T Insert<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure);  
  19.         T Update<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure);  
  20.     }  
  21. }  
In the Helper folder, add a new class namely "DapperHelper" and copy the below code and paste in that class. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using Dapper;  
  5. using Microsoft.Extensions.Configuration;  
  6. using System.Data;  
  7. using System.Data.Common;  
  8. using System.Data.SqlClient;  
  9. using System.Linq.Expressions;  
  10. using static Dapper.SqlMapper;  
  11. using CoreDemo_3_0.Interfaces;  
  12.   
  13. namespace CoreDemo_3_0.Helper  
  14. {  
  15.     public class DapperHelper : IDapperHelper  
  16.     {  
  17.         private readonly IConfiguration _config;  
  18.         public DapperHelper(IConfiguration config)  
  19.         {  
  20.             _config = config;  
  21.         }  
  22.   
  23.         public DbConnection GetConnection()  
  24.         {  
  25.             return new SqlConnection(_config.GetConnectionString("DefaultConnection"));  
  26.         }  
  27.   
  28.         public T Get<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
  29.         {  
  30.             using (IDbConnection db = new SqlConnection(_config.GetConnectionString("DefaultConnection")))  
  31.             {  
  32.                 return db.Query<T>(sp, parms, commandType: commandType).FirstOrDefault();  
  33.             }  
  34.         }  
  35.   
  36.         public List<T> GetAll<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
  37.         {  
  38.             using (IDbConnection db = new SqlConnection(_config.GetConnectionString("DefaultConnection")))  
  39.             {  
  40.                 return db.Query<T>(sp, parms, commandType: commandType).ToList();  
  41.             }  
  42.         }  
  43.   
  44.         public int Execute(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
  45.         {  
  46.             using (IDbConnection db = new SqlConnection(_config.GetConnectionString("DefaultConnection")))  
  47.             {  
  48.                 return db.Execute(sp, parms, commandType: commandType);  
  49.             }  
  50.         }         
  51.   
  52.         public T Insert<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
  53.         {  
  54.             T result;  
  55.             using (IDbConnection db = new SqlConnection(_config.GetConnectionString("DefaultConnection")))  
  56.             {  
  57.                 try  
  58.                 {  
  59.                     if (db.State == ConnectionState.Closed)  
  60.                         db.Open();  
  61.   
  62.                     using (var tran = db.BeginTransaction())  
  63.                     {  
  64.                         try  
  65.                         {  
  66.                             result = db.Query<T>(sp, parms, commandType: commandType, transaction: tran).FirstOrDefault();  
  67.                             tran.Commit();  
  68.                         }  
  69.                         catch (Exception ex)  
  70.                         {  
  71.                             tran.Rollback();  
  72.                             throw ex;  
  73.                         }  
  74.                     }  
  75.                 }  
  76.                 catch (Exception ex)  
  77.                 {  
  78.                     throw ex;  
  79.                 }  
  80.                 finally  
  81.                 {  
  82.                     if (db.State == ConnectionState.Open)  
  83.                         db.Close();  
  84.                 }  
  85.   
  86.                 return result;  
  87.             }  
  88.         }  
  89.   
  90.         public T Update<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)  
  91.         {  
  92.             T result;  
  93.             using (IDbConnection db = new SqlConnection(_config.GetConnectionString("DefaultConnection")))  
  94.             {  
  95.                 try  
  96.                 {  
  97.                     if (db.State == ConnectionState.Closed)  
  98.                         db.Open();  
  99.   
  100.                     using (var tran = db.BeginTransaction())  
  101.                     {  
  102.                         try  
  103.                         {  
  104.                             result = db.Query<T>(sp, parms, commandType: commandType, transaction: tran).FirstOrDefault();  
  105.                             tran.Commit();  
  106.                         }  
  107.                         catch (Exception ex)  
  108.                         {  
  109.                             tran.Rollback();  
  110.                             throw ex;  
  111.                         }  
  112.                     }  
  113.                 }  
  114.                 catch (Exception ex)  
  115.                 {  
  116.                     throw ex;  
  117.                 }  
  118.                 finally  
  119.                 {  
  120.                     if (db.State == ConnectionState.Open)  
  121.                         db.Close();  
  122.                 }  
  123.   
  124.                 return result;  
  125.             }  
  126.         }  
  127.   
  128.           
  129.         public void Dispose()  
  130.         {  
  131.             throw new NotImplementedException();  
  132.         }  
  133.     }  
  134. }  

Here, we created a Dapper helper which we will use to communicate with the database.

Step 6 - Create a Context class
 
Create a new folder named "Context" and add one class "DataContext" which extends from the DbContext class.
 
Copy the below code and paste inside "DataContext" class.
  1. using CoreDemo_3_0.Entities;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace CoreDemo_3_0.Context  
  9. {  
  10.     public class DataContext : DbContext  
  11.     {  
  12.         public DataContext() { }  
  13.   
  14.         public DataContext(DbContextOptions<DataContext> options) : base(options) { }  
  15.     }  
  16.   
  17.   
  18. }  
Step 7
 
Create one folder named "Entities" and add a class, namely "Job".
 
Copy the below code and paste into the "Job" class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace CoreDemo_3_0.Entities  
  8. {  
  9.     public class Job  
  10.     {  
  11.         [Key]  
  12.         public int JobID { getset; }  
  13.         public string JobTitle { getset; }  
  14.         public int CityId { getset; }  
  15.         public string JobImage { getset; }  
  16.         public bool IsActive { getset; }  
  17.         public string CreatedBY { getset; }  
  18.         public DateTime? CreatedDateTime { getset; }  
  19.         public string UpdatedBY { getset; }  
  20.         public DateTime? UpdatedDateTime { getset; }  
  21.     }  
  22.      
  23. }  
Step 8 
 
Create one folder named "Models" and add a class "JobModel".

Copy the below code and paste into "JobModel" class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace CoreDemo_3_0.Models  
  7. {  
  8.     public class JobModel  
  9.     {  
  10.         public int JobID { getset; }         
  11.         public string JobTitle { getset; }  
  12.         public int CityId { getset; }  
  13.         public string JobImage { getset; }  
  14.         public bool IsActive { getset; }  
  15.         public string CreatedBY { getset; }  
  16.         public DateTime? CreatedDateTime { getset; }  
  17.         public string UpdatedBY { getset; }  
  18.         public DateTime? UpdatedDateTime { getset; }  
  19.         public int JobState { getset; }         
  20.     }  
  21. }  

Step 9 - Add IJob interface

Add IJob interface, "IJobService" inside the interface folder which we created before. Below is the code of the interface.
  1. using CoreDemo_3_0.Entities;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace CoreDemo_3_0.Interfaces  
  8. {  
  9.     public interface IJobService  
  10.     {  
  11.         int Delete(int JobId);  
  12.         Job GetByJobId(int JobId);  
  13.         string Update(Job job);  
  14.         int Create(Job JobDetails);  
  15.         List<Job> ListAll();  
  16.     }  
  17. }  

Step 10 - Add Job service

Add a new folder named "Services" and one class inside that folder. The class name will be "JobService". Below is the JobService class code.
  1. using CoreDemo_3_0.Entities;  
  2. using CoreDemo_3_0.Interfaces;  
  3. using Dapper;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Data;  
  7. using System.Linq;  
  8. using System.Threading.Tasks;  
  9. using System.Transactions;  
  10.   
  11. namespace CoreDemo_3_0.Services  
  12. {  
  13.     public class JobService : IJobService  
  14.     {  
  15.         private readonly IDapperHelper _dapperHelper;  
  16.   
  17.         public JobService(IDapperHelper dapperHelper)  
  18.         {  
  19.             this._dapperHelper = dapperHelper;  
  20.         }  
  21.   
  22.         public int Create(Job job)  
  23.         {  
  24.             var dbPara = new DynamicParameters();  
  25.             dbPara.Add("JobTitle", job.JobTitle, DbType.String);  
  26.             dbPara.Add("JobImage", job.JobImage, DbType.String);  
  27.             dbPara.Add("CityId", job.CityId, DbType.Int32);  
  28.             dbPara.Add("IsActive", job.IsActive, DbType.String);  
  29.             dbPara.Add("CreatedBY""1", DbType.String);  
  30.             dbPara.Add("CreatedDateTime", DateTime.Now, DbType.DateTime);  
  31.             dbPara.Add("UpdatedBY""1", DbType.String);  
  32.             dbPara.Add("UpdatedDateTime", DateTime.Now, DbType.DateTime);  
  33.  
  34.             #region using dapper  
  35.             var data = _dapperHelper.Insert<int>("[dbo].[SP_Add_Job]",  
  36.                             dbPara,  
  37.                             commandType: CommandType.StoredProcedure);  
  38.             return data;  
  39.             #endregion  
  40.   
  41.         }  
  42.   
  43.         public Job GetByJobId(int JobId)  
  44.         {  
  45.             #region using dapper  
  46.             var data = _dapperHelper.Get<Job>($"select * from job  where JobId={JobId}"null,  
  47.                     commandType: CommandType.Text);  
  48.             return data;  
  49.             #endregion  
  50.   
  51.   
  52.         }  
  53.   
  54.         public int Delete(int JobId)  
  55.         {  
  56.             var data = _dapperHelper.Execute($"Delete [Job] where JObId={JobId}"null,  
  57.                     commandType: CommandType.Text);  
  58.             return data;  
  59.         }  
  60.   
  61.         public List<Job> ListAll()  
  62.         {  
  63.             var data = _dapperHelper.GetAll<Job>("[dbo].[SP_Job_List]"null, commandType: CommandType.StoredProcedure);  
  64.             return data.ToList();  
  65.   
  66.         }  
  67.   
  68.         public string Update(Job job)  
  69.         {  
  70.             var dbPara = new DynamicParameters();  
  71.             dbPara.Add("JobTitle", job.JobTitle, DbType.String);  
  72.             dbPara.Add("JobId", job.JobID);  
  73.             dbPara.Add("JobImage", job.JobImage, DbType.String);  
  74.             dbPara.Add("CityId", job.CityId, DbType.Int32);  
  75.             dbPara.Add("IsActive", job.IsActive, DbType.String);  
  76.             dbPara.Add("UpdatedBY""1", DbType.String);  
  77.             dbPara.Add("UpdatedDateTime", DateTime.Now, DbType.DateTime);  
  78.   
  79.   
  80.             var data = _dapperHelper.Update<string>("[dbo].[SP_Update_Job]",  
  81.                             dbPara,  
  82.                             commandType: CommandType.StoredProcedure);  
  83.             return data;  
  84.   
  85.   
  86.         }  
  87.     }  
  88. }  
Step 11 - Add Connection String
 
Add a connection string into the appsettings.json file. Here is the code of the appsettings.json file. 
  1. {  
  2.   "ConnectionStrings": {  
  3.     "DefaultConnection""data source=.;initial catalog=CoreMaster;User Id=sa;Password=******;"  
  4.   },  
  5.   "Logging": {  
  6.     "LogLevel": {  
  7.       "Default""Warning",  
  8.       "Microsoft.Hosting.Lifetime""Information"  
  9.     }  
  10.   },  
  11.   "AllowedHosts""*"  
  12. }  
Step 12 - Changes in Startup class
 
Now, we need to add a connection string context and register our services.
 
Code to add connectionstring -
  1. services.AddDbContext<DataContext>(options =>  
  2.               options.UseSqlServer(  
  3.                   Configuration.GetConnectionString("DefaultConnection")));  
Add a service to scoped.
  1.  //Job service  
  2. services.AddScoped<IJobService, JobService>();  
  3.   
  4. //Register dapper in scope  
  5. services.AddScoped<IDapperHelper, DapperHelper>();  
Step 13 - Add Controller
 
It's now time to add a Job Controller inside the Controllers folder. Below is the full code of JobController.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Net.Http.Headers;  
  6. using System.Threading.Tasks;  
  7. using CoreDemo_3_0.Entities;  
  8. using CoreDemo_3_0.Interfaces;  
  9. using CoreDemo_3_0.Models;  
  10. using Microsoft.AspNetCore.Hosting;  
  11. using Microsoft.AspNetCore.Mvc;  
  12.   
  13. namespace CoreDemo_3_0.Controllers  
  14. {  
  15.     public class JobController : Controller  
  16.     {  
  17.         private readonly IJobService _jobManager;  
  18.         private readonly IHostingEnvironment _hostingEnvironment;  
  19.   
  20.         public JobController(IJobService jobManager, IHostingEnvironment hostingEnvironment)  
  21.         {  
  22.             _jobManager = jobManager;  
  23.             _hostingEnvironment = hostingEnvironment;  
  24.         }  
  25.   
  26.         public ActionResult Index()  
  27.         {  
  28.             var data = _jobManager.ListAll();  
  29.   
  30.             string baseUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";  
  31.             foreach (var item in data)  
  32.             {  
  33.                 if (!string.IsNullOrEmpty(item.JobImage))  
  34.                     item.JobImage = Path.Combine(baseUrl, "Images", item.JobImage);  
  35.                 else  
  36.                     item.JobImage = Path.Combine(baseUrl, "Images""404.png");  
  37.             }  
  38.             return View(data);  
  39.         }  
  40.  
  41.         #region Add Job  
  42.   
  43.         public ActionResult Add()  
  44.         {  
  45.             return View("Form"new JobModel());  
  46.         }  
  47.   
  48.         [HttpPost]  
  49.         [ValidateAntiForgeryToken]  
  50.         public ActionResult Add(JobModel model)  
  51.         {  
  52.             if (ModelState.IsValid)  
  53.             {  
  54.                 var fileName = "";  
  55.                 if (Request.Form.Files.Count > 0)  
  56.                 {  
  57.                     var file = Request.Form.Files[0];  
  58.                     var webRootPath = _hostingEnvironment.WebRootPath;  
  59.                     var newPath = Path.Combine(webRootPath, "images");  
  60.                     if (!Directory.Exists(newPath)) Directory.CreateDirectory(newPath);  
  61.   
  62.                     if (file.Length > 0)  
  63.                     {  
  64.                         fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');  
  65.                         var fullPath = Path.Combine(newPath, fileName);  
  66.                         using (var stream = new FileStream(fullPath, FileMode.Create))  
  67.                         {  
  68.                             file.CopyTo(stream);  
  69.                         }  
  70.                     }  
  71.                 }  
  72.   
  73.                 var job = new Job()  
  74.                 {  
  75.                     CityId = model.CityId,  
  76.                     JobImage = fileName,  
  77.                     CreatedBY = "1",  
  78.                     CreatedDateTime = DateTime.Now,  
  79.                     JobTitle = model.JobTitle,  
  80.                     UpdatedBY = "1",  
  81.                     IsActive = model.IsActive,  
  82.                     UpdatedDateTime = DateTime.Now  
  83.                 };  
  84.   
  85.                 _jobManager.Create(job);  
  86.                 return RedirectToAction("Index""Job");  
  87.             }  
  88.             return View("Form", model);  
  89.         }  
  90.  
  91.         #endregion  
  92.  
  93.         #region Edit Job  
  94.   
  95.         public ActionResult Edit(int JobId)  
  96.         {  
  97.             var jobEntity = _jobManager.GetByJobId(JobId);  
  98.             var jobModel = new JobModel  
  99.             {  
  100.                 JobID = jobEntity.JobID,  
  101.                 CityId = jobEntity.CityId,  
  102.                 JobImage = jobEntity.JobImage,  
  103.                 CreatedBY = jobEntity.CreatedBY,  
  104.                 CreatedDateTime = jobEntity.CreatedDateTime,  
  105.                 JobTitle = jobEntity.JobTitle,  
  106.                 UpdatedBY = jobEntity.UpdatedBY,  
  107.                 IsActive = jobEntity.IsActive,  
  108.                 UpdatedDateTime = jobEntity.UpdatedDateTime  
  109.             };  
  110.             return View("Form", jobModel);  
  111.         }  
  112.   
  113.         [HttpPost]  
  114.         [ValidateAntiForgeryToken]  
  115.         public ActionResult Edit(JobModel model)  
  116.         {  
  117.             if (ModelState.IsValid)  
  118.             {  
  119.                 var fileName = model.JobImage ?? "";  
  120.                 if (Request.Form.Files.Count > 0)  
  121.                 {  
  122.                     var file = Request.Form.Files[0];  
  123.                     var webRootPath = _hostingEnvironment.WebRootPath;  
  124.                     var newPath = Path.Combine(webRootPath, "images");  
  125.                     if (!Directory.Exists(newPath)) Directory.CreateDirectory(newPath);  
  126.   
  127.                     if (file.Length > 0)  
  128.                     {  
  129.                         fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');  
  130.                         var fullPath = Path.Combine(newPath, fileName);  
  131.                         using (var stream = new FileStream(fullPath, FileMode.Create))  
  132.                         {  
  133.                             file.CopyTo(stream);  
  134.                         }  
  135.                     }  
  136.                 }  
  137.   
  138.                 var job = new Job()  
  139.                 {  
  140.                     JobID = model.JobID,  
  141.                     CityId = model.CityId,  
  142.                     JobImage = fileName,  
  143.                     JobTitle = model.JobTitle,  
  144.                     UpdatedBY = "1",  
  145.                     IsActive = model.IsActive,  
  146.                 };  
  147.   
  148.                 _jobManager.Update(job);  
  149.                 return RedirectToAction("Index""Job");  
  150.             }  
  151.             return View("Form", model);  
  152.         }  
  153.  
  154.         #endregion  
  155.  
  156.         #region Delete Job  
  157.   
  158.         public ActionResult Delete(int JobId)  
  159.         {  
  160.             var jobEntity = _jobManager.Delete(JobId);  
  161.             return RedirectToAction("Index""Job");  
  162.         }  
  163.  
  164.         #endregion  
  165.   
  166.     }  
  167. }  
Step 14 - Add Views
 
It is time to add a ViewController inside Views > Job folder. Below is the code for all views of JobController.
 
Form.cshtml
  1. @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers  
  2. @model CoreDemo_3_0.Models.JobModel  
  3. @{  
  4.     ViewData["Title"] = "Add Job";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <div class="row">  
  9.     <!-- left column -->  
  10.     <div class="col-md-12">  
  11.         <!-- general form elements -->  
  12.         <div class="box box-primary">  
  13.             <!-- form start -->  
  14.             @using (Html.BeginForm(Model.JobID == 0 ? "Add" : "Edit", "Job", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  15.             {  
  16.                 <div class="box-body">  
  17.                     @Html.AntiForgeryToken()  
  18.                     <div class="row">  
  19.                         @Html.HiddenFor(model => model.JobID)  
  20.                         <div class="col-xs-12" f>  
  21.                             <label>Job Title</label>  
  22.                             @Html.TextBoxFor(model => model.JobTitle, new { @class = "form-control", @placeholder = "Job Title" })  
  23.                         </div>  
  24.                     </div>  
  25.                     <br />                      
  26.                     <div class="row">  
  27.                         <div class="col-xs-12">  
  28.                             <label>Enter City ID</label>  
  29.                             @Html.TextBoxFor(model => model.CityId, new { @class = "form-control" })  
  30.   
  31.                         </div>  
  32.                     </div>  
  33.                     <br />  
  34.                     <div class="row">  
  35.                         <div class="col-xs-12">  
  36.                             <label>Job Image</label>  
  37.                             <input type="file" id="file" name="file">  
  38.                             @Html.HiddenFor(model => model.JobImage)  
  39.                         </div>  
  40.                     </div>  
  41.                     <div class="row">  
  42.                         <div class="col-xs-12">  
  43.                             @Html.CheckBoxFor(model => model.IsActive, new { @class = "col-form-checkbox" })  Vacancy Available  
  44.                         </div>  
  45.                     </div>  
  46.                 </div><!-- /.box-body -->  
  47.                 <div class="box-footer">  
  48.                     <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Save</button>  
  49.                 </div>  
  50.             }  
  51.         </div>  
  52.     </div>  
  53. </div>  
Index.cshtml
  1. @model List<CoreDemo_3_0.Entities.Job>  
  2. @{  
  3.     ViewData["Title"] = "Job List";  
  4. }  
  5. <a href="/Job/Add" class="btn btn-primary">Add</a>  
  6. <br />  
  7. <table id="_DataTable" class="table compact table-striped table-bordered nowrap dataTable" aria-describedby="_DataTable_info">  
  8.     <thead>  
  9.         <tr role="row">  
  10.             <th class="sorting_asc" role="columnheader" tabindex="0" aria-controls="_DataTable" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Image: activate to sort column descending" style="width: 127px;">Image</th>  
  11.             <th class="sorting" role="columnheader" tabindex="0" aria-controls="_DataTable" rowspan="1" colspan="1" aria-label="Title: activate to sort column ascending" style="width: 209px;">Title</th>  
  12.             <th class="sorting" role="columnheader" tabindex="0" aria-controls="_DataTable" rowspan="1" colspan="1" aria-label="City: activate to sort column ascending" style="width: 116px;">City</th>  
  13.             <th class="sorting" role="columnheader" tabindex="0" aria-controls="_DataTable" rowspan="1" colspan="1" aria-label="Vacancy: activate to sort column ascending" style="width: 127px;">Vacancy</th>  
  14.             <th class="sorting" role="columnheader" tabindex="0" aria-controls="_DataTable" rowspan="1" colspan="1" aria-label="Created Date: activate to sort column ascending" style="width: 190px;">Created Date</th>  
  15.             <th style="width: 38px;" class="sorting" role="columnheader" tabindex="0" aria-controls="_DataTable" rowspan="1" colspan="1" aria-label=" Action : activate to sort column ascending"> Action </th>  
  16.         </tr>  
  17.     </thead>  
  18.     <tbody role="alert" aria-live="polite" aria-relevant="all">  
  19.         @foreach (var item in Model)  
  20.         {  
  21.             <tr class="even">  
  22.                 <td style="text-align:left"><img src="@item.JobImage" alt="Image" width="50" height="50"></td>  
  23.                 <td style="text-align:left">@item.JobTitle</td>  
  24.                 <td style="text-align:left">@item.CityId</td>  
  25.                 <td style="text-align:left">@(item.IsActive == true ? "Yes" : "No")</td>  
  26.     <td style="text-align:right">@item.CreatedDateTime</td>  
  27.     <td class="text-center ">  
  28.         <a href="/Job/Edit?JobID=@item.JobID" title="Edit">Edit  <i class="fa fa-edit"></i></a><a href="/Job/Delete?&JobID=@item.JobID" class="" onclick="return confirm(" Are you sure you want to delete this job?");" title="Delete">Delete     <i class="fa fa-times"></i></a>  
  29.     </td>  
  30. </tr>  
  31.                 }  
  32.   
  33.             </tbody>  
  34.         </table>  

Output 

  1. Index Page

    CRUD Operations In .NET Core 3.0 With Visual Studio 2019

  2. Add Page

    CRUD Operations In .NET Core 3.0 With Visual Studio 2019

  3. Edit Page

    CRUD Operations In .NET Core 3.0 With Visual Studio 2019

Summary

Here, we created a simple application that uses the dapper, Core 3.0 preview, SQL Server, and Visual Studio 2019 to perform CRUD operations. You can leave the feedback/comment/questions about this article below. Please let me know how you like and understand this article and how I could improve it.