In this article, we will learn CRUD operation in ASP.NET Core using Dapper ORM step by step. Creating CRUD operation for GroupMetting Application in ASP.NET Core using Visual Studio 2017 with Dapper ORM.
We will use Visual Studio 2017 to develop the web application using ASP.NET Core with Razor pages. If you don’t have a basic idea of ASP.NET Core and how to set up an ASP.NET Core Environment. How to install Visual Studio 2017. Then Please go with my previous article click What ASP.NET Core Is And set up ASP.NET Core Environment.
Before proceeding further please refer to my previous articles for a better understanding.
- What ASP.NET Core Is And set up ASP.NET Core Environment.
- CRUD Operation In ASP.NET Core Using ADO.NET
Prerequisites:
• SQL Server 2012 or above
What's Dapper?
Dapper is a simple object mapper for .NET and owns the title of "King of Micro ORM" in terms of speed. An ORM is an Object Relational Mapper, which is responsible for mapping between database and programming language.
There are three steps to working with Dapper as follows,
- Create an IDbConnection object.
- Write a query to perform CRUD operations.
- Pass query as a parameter in Execute method.
We will create one small "Group Meeting" web application in ASP.NET Core using Dapper ORM as follow.
First of all, Create Database scripts as follow
Scripts 1:
To create the database.
To create the database.
CREATE DATABASE ProjectMeeting
Scripts 2:
To create the database table named “GroupMeeting”.
USE [ProjectMeeting]
GO
/****** Object: Table [dbo].[GroupMeeting] Script Date: 07-09-2019 22:01:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[GroupMeeting](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ProjectName] [varchar](50) NULL,
[GroupMeetingLeadName] [varchar](50) NULL,
[TeamLeadName] [varchar](50) NULL,
[Description] [varchar](50) NULL,
[GroupMeetingDate] [date] NULL,
CONSTRAINT [PK_GroupMeeting-2] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
Scripts 3:
Create the stored procedure to get all the group meeting in detail.
USE [ProjectMeeting]
GO
/****** Object: StoredProcedure [dbo].[GetGroupMeetingDetails] Script Date: 07-09-2019 22:05:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [dbo].[GetGroupMeetingDetails]
AS
BEGIN
SELECT * FROM GROUPMEETING
END
GO
Scripts 4:
Create the stored procedure to get the group meeting by Id.
USE [ProjectMeeting]
GO
/****** Object: StoredProcedure [dbo].[GetGroupMeetingByID] Script Date: 07-09-2019 22:13:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [dbo].[GetGroupMeetingByID](@Id int)
AS
BEGIN
SELECT * FROM GROUPMEETING where id=@Id
END
GO
Scripts 5:
Step 10:
As of now, we have completed the model related changes Get, Insert, Update, Delete using dapper ORM in the above code.
Provide the meaning full name like “GroupMeeting” as follow.
Create a stored procedure to create a new group meeting.
USE [ProjectMeeting]
GO
/****** Object: StoredProcedure [dbo].[InsertGroupMeeting] Script Date: 07-09-2019 22:17:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[InsertGroupMeeting]
(
@ProjectName varchar(50),
@GroupMeetingLeadName varchar(50),
@TeamLeadName varchar(50),
@Description varchar(50),
@GroupMeetingDate date
)
As
BEGIN
INSERT INTO GroupMeeting(ProjectName,GroupMeetingLeadName,TeamLeadName,Description,GroupMeetingDate) VALUES(@ProjectName,@GroupMeetingLeadName,@TeamLeadName,@Description,@GroupMeetingDate)
END
GO
Scripts 6:
Create the stored procedure to update the group meeting.
USE [ProjectMeeting]
GO
/****** Object: StoredProcedure [dbo].[UpdateGroupMeeting] Script Date: 07-09-2019 22:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[UpdateGroupMeeting]
(
@Id int,
@ProjectName varchar(50),
@GroupMeetingLeadName varchar(50),
@TeamLeadName varchar(50),
@Description varchar(50),
@GroupMeetingDate date
)
As
BEGIN
UPDATE GroupMeeting
SET ProjectName =@ProjectName,
GroupMeetingLeadName =@GroupMeetingLeadName,
TeamLeadName = @TeamLeadName,
Description = @Description,
GroupMeetingDate =@GroupMeetingDate
Where Id=@Id
END
GO
Scripts 7:
Create the stored procedure to delete the group meeting.
USE [ProjectMeeting]
GO
/****** Object: StoredProcedure [dbo].[DeleteGroupMeeting] Script Date: 07-09-2019 22:27:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[DeleteGroupMeeting]
(
@Id int
)
As
BEGIN
DELETE FROM GroupMeeting WHERE Id=@Id
END
GO
Now, we have completed our database related changes. Let’s we can go with codebase changes using visual studio 2017.
Step 1:
Open the Visual Studio 2017.
Step 2:
Click on File => Open => New Project as shown in the image.
Step 3:
Select .NET Core from the left side and select the ‘ASP.NET Core Web. Application’ from the new open project template. Then provide the meaning name like “GroupMeetingASP.NETCoreWebApp”.
Step 4:
Select the Web Application(MVC) template from the list of templates and click on the "OK" button as follow.
Step 5:
The default ASP.NET Core MVC structure gets created as follow. The default model, view, controller get created default.
Step 6:
Right click on Models => Click on Add => Click on Class.
Step 7:
Provide the meaning full name like “GroupMeeting” and click on "Add" button as follow.
To work with dapper need to install dapper ORM using 'Manage Nuget Package'
Step 1:
Right-click on Solution Manager => Click on 'Manage Nuget Package' as shown in the figure.
Step 2:
Select 'Browse' and type dapper in the search box => Enter => Select the dapper and Click on Install as shown in the figure.
After successful installation of dapper ORM:
In order to work with Dapper ORM import namespace as follow.
using Dapper;
Step 8:
Write code to create properties for group meeting class as follow. Also, use the Required attribute to validate the class fields.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel.DataAnnotations;
using Dapper;
public class GroupMeeting
{
public int GroupMeetingId { get; set; }
[Required(ErrorMessage = "Enter Project Name!")]
public string ProjectName { get; set; }
[Required(ErrorMessage = "Enter Group Lead Name!")]
public string GroupMeetingLeadName { get; set; }
[Required(ErrorMessage = "Enter Team Lead Name!")]
public string TeamLeadName { get; set; }
[Required(ErrorMessage = "Enter Description!")]
public string Description { get; set; }
[Required(ErrorMessage = "Enter Group Meeting Date!")]
public DateTime GroupMeetingDate { get; set; }
static string strConnectionString = "User Id=sa;Password=Shri;Server=Shri\\SQL2014;Database=ProjectMeeting;";
}
Step 9:
Write code in GroupMeeting class to get all group meeting detail from the database using the stored procedure with dapper ORM. The method name is "GetGroupMeetings()" and return type is IEnumerable<GroupMeeting> or List<GroupMeeting> you can use either one of them.
public static IEnumerable<GroupMeeting> GetGroupMeetings()
{
List<GroupMeeting> groupMeetingsList = new List<GroupMeeting>();
using (IDbConnection con = new SqlConnection(strConnectionString))
{
if (con.State == ConnectionState.Closed)
con.Open();
groupMeetingsList = con.Query<GroupMeeting>("GetGroupMeetingDetails").ToList();
}
return groupMeetingsList;
}
Add code in GroupMeeting class for getting group meeting detail by groupId as follow:
public static GroupMeeting GetGroupMeetingById(int? id)
{
GroupMeeting groupMeeting = new GroupMeeting();
if (id == null)
return groupMeeting;
using (IDbConnection con = new SqlConnection(strConnectionString))
{
if (con.State == ConnectionState.Closed)
con.Open();
DynamicParameters parameter = new DynamicParameters();
parameter.Add("@Id", id);
groupMeeting = con.Query<GroupMeeting>("GetGroupMeetingByID", parameter, commandType: CommandType.StoredProcedure).FirstOrDefault();
}
return groupMeeting;
}
Step 10:
Add code in GroupMeeting class to Insert the group meeting using dapper as follow.
method name is 'AddGroupMeeting()' and integer return type. For Insert or update in Dapper ORM, we can pass the parameter to the query using DynamicParameters as follow. with the help of Execute(), we can perform Insert or update Operation in the database.
public static int AddGroupMeeting(GroupMeeting groupMeeting)
{
int rowAffected = 0;
using (IDbConnection con = new SqlConnection(strConnectionString))
{
if (con.State == ConnectionState.Closed)
con.Open();
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@ProjectName", groupMeeting.ProjectName);
parameters.Add("@GroupMeetingLeadName", groupMeeting.GroupMeetingLeadName);
parameters.Add("@TeamLeadName", groupMeeting.TeamLeadName);
parameters.Add("@Description", groupMeeting.Description);
parameters.Add("@GroupMeetingDate", groupMeeting.GroupMeetingDate);
rowAffected = con.Execute("InsertGroupMeeting", parameters, commandType: CommandType.StoredProcedure);
}
return rowAffected;
}
Code to Update the group meeting in GroupMeeting class using dapper as follow.
update in Dapper ORM, we can pass the parameter to the query/stored procedure using DynamicParameters as follow. with the help of Execute(), we can perform Insert or update Operation in the database.
public static int UpdateGroupMeeting(GroupMeeting groupMeeting)
{
int rowAffected = 0;
using (IDbConnection con = new SqlConnection(strConnectionString))
{
if (con.State == ConnectionState.Closed)
con.Open();
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", groupMeeting.Id);
parameters.Add("@ProjectName", groupMeeting.ProjectName);
parameters.Add("@GroupMeetingLeadName", groupMeeting.GroupMeetingLeadName);
parameters.Add("@TeamLeadName", groupMeeting.TeamLeadName);
parameters.Add("@Description", groupMeeting.Description);
parameters.Add("@GroupMeetingDate", groupMeeting.GroupMeetingDate);
rowAffected = con.Execute("UpdateGroupMeeting", parameters, commandType: CommandType.StoredProcedure);
}
return rowAffected;
}
Code to Delete the group meeting using dapper as follow.
For Delete in Dapper ORM, we can pass the parameter to the query/stored procedure using DynamicParameters as follow. with the help of Execute(), we can perform delete operation from the database.
public static int DeleteGroupMeeting(int id)
{
int rowAffected = 0;
using (IDbConnection con = new SqlConnection(strConnectionString))
{
if (con.State == ConnectionState.Closed)
con.Open();
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
rowAffected = con.Execute("DeleteGroupMeeting", parameters, commandType: CommandType.StoredProcedure);
}
return rowAffected;
}
As of now, we have completed the model related changes Get, Insert, Update, Delete using dapper ORM in the above code.
Step 11:
Right click on Controller folder => Click on “Add” => Click on Controller as follow.
Step 12:
Select MVC Controller Empty and click on add button as follow.
Step 13:
After the adding controller, you need to import the required namespace. Then added the following code to get all group meeting detail and pass to the view as follow.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using GroupMeetingASP.NETCoreWebApp.Models;
namespace GroupMeetingASP.NETCoreWebApp.Controllers
{
public class GroupMeetingController : Controller
{
public IActionResult Index()
{
return View(GroupMeeting.GetGroupMeetings());
}
}
}
Step 14:
Right-click on ActionResult and click on Add view as follow.
Step 15:
Write code for displaying group meeting data on Index.cshtml view as follow.
@model IEnumerable<GroupMeetingASP.NETCoreWebApp.Models.GroupMeeting>
@{
ViewData["Title"] = "Index";
}
<h4>Group MeetingWeb App</h4><hr />
<h4>
<a asp-action="AddGroupMeeting"> AddGroupMeeting</a>
</h4>
<div>
<tableclass ="table table-responsive table-bordered panel-primary">
<thead>
<th>Project Name</th>
<th>Group LeadName</th>
<th>Team LeadName</th>
<th>Description</th>
<th>Meeting Date</th>
<th></th>
</thead>
<tbody>
@foreach (var itemin Model)
{
< tr >
< td > @Html.DisplayFor(model => item.ProjectName) </ td >
< td > @Html.DisplayFor(model => item.GroupMeetingLeadName) </ td >
< td > @Html.DisplayFor(model => item.TeamLeadName) </ td >
< td > @Html.DisplayFor(model => item.Description) </ td >
< td > @Html.DisplayFor(model => item.GroupMeetingDate) </ td >
< td >
< a asp - action = "EditMeeting"asp - route - id = "@item.GroupMeetingId" > Edit </ a >|
< a asp - action = "DeleteMeeting"asp - route - id = "@item.GroupMeetingId" > Delete </ a >
</ td >
</ tr >
}
</tbody>
</table>
</div>
Click on Startup.cs file and change the Controller name as "GroupMeeting" controller as follow.
app.UseMvc(routes=>
{
routes.MapRoute(
name: "default",
template: "{controller=GroupMeeting}/{action=Index}/{id?}");
});
After changes the controller name in the startup.cs file click on IIS Express to run the application OR F5.
The output of index page as follow.
Step 16:
We will create “AddGroupMeeting” view in the GroupMeeting controller And write the following code. We have written two views first is "HttpGet" and "HttpPost" as follow.
[HttpGet]
public IActionResult AddGroupMeeting()
{
return View();
}
[HttpPost]
public IActionResult AddGroupMeeting([Bind]GroupMeeting groupMeeting)
{
if (ModelState.IsValid)
{
if (GroupMeeting.AddGroupMeeting(groupMeeting) > 0)
{
return RedirectToAction("Index");
}
}
return View(groupMeeting);
}
Step 17:
We will create “AddGroupMeeting.cshtml” view and write the code to add the group meeting detail as follow.
@model GroupMeetingASP.NETCoreWebApp.Models.GroupMeeting
@{
ViewData["Title"] = "AddGroupMeeting";
}
<h2>Add GroupMeeting</h2>
<div class="row">
<div class="col-md-4">
<form asp-action="AddGroupMeeting">
<div class="">
<label asp-for="ProjectName" class="control-label"></label>
<input asp-for="ProjectName" class="form-control" />
<span class="alert-danger" asp-validation-for="ProjectName"></span>
</div>
<div class="form-group">
<label asp-for="GroupMeetingLeadName" class="control-label"></label>
<input asp-for="GroupMeetingLeadName" class="form-control" />
<span class="alert-danger" asp-validation-for="GroupMeetingLeadName"></span>
</div>
<div class="form-group">
<label asp-for="TeamLeadName" class="control-label"></label>
<input asp-for="TeamLeadName" class="form-control" />
<span class="alert-danger" asp-validation-for="TeamLeadName"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<input asp-for="Description" class="form-control" />
<span class="alert-danger" asp-validation-for="Description"></span>
</div>
<div class="form-group">
<label asp-for="GroupMeetingDate" class="control-label"></label>
<input asp-for="GroupMeetingDate" class="form-control" />
<span class="alert-danger" asp-validation-for="GroupMeetingDate"></span>
</div>
<div class="form-group">
<input type="submit" value="Create Meeting" class="btn btn-success btn-sm" />
</div>
</form>
</div>
<div class="col-md-8">
</div>
</div>
<div>
<a asp-action="Index">Back ToHome</a>
</div>
"AddGroupMeeting" view display as follow.
We have also added the validation using DataAnnotations in ASP.NET Core on add group meeting page.
Enter the valid information in the group meeting page and click on “Create Meeting” button. Then it will redirect to the index view page.
Step 18:
We will create “EditMeeting” view in the GroupMeeting Controller and write the code to edit the group meeting detail as follow.
There are two views of EditMeeting "HttpGet" and "HttpPost". The "HttpGet" edit meeting view having id as a parameter gets called when clicking on "Edit" button on the index view page.
[HttpGet]
public IActionResult EditMeeting(int? id)
{
if (id == null)
{
return NotFound();
}
GroupMeeting group = GroupMeeting.GetGroupMeetingById(id);
if (group == null)
return NotFound();
return View(group);
}
[HttpPost]
public IActionResult EditMeeting(int id, [Bind]GroupMeeting groupMeeting)
{
if (id != groupMeeting.GroupMeetingId)
return NotFound();
if (ModelState.IsValid)
{
GroupMeeting.UpdateGroupMeeting(groupMeeting);
return RedirectToAction("Index");
}
return View(groupMeeting);
}
We will create “EditMeeting.cshtml” view and write code as follow.
@model GroupMeetingASP.NETCoreWebApp.Models.GroupMeeting
@{
ViewData["Title"] = "EditMeeting";
}
<h4>Update the Meeting</h4>
<div class="row">
<div class="col-md-4">
<form asp-action="EditMeeting">
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="ProjectName" class="control-label"></label>
<input asp-for="ProjectName" class="form-control" />
</div>
<div class="form-group">
<label asp-for="GroupMeetingLeadName" class="control-label"></label>
<input asp-for="GroupMeetingLeadName" class="form-control" />
</div>
<div class="form-group">
<label asp-for="TeamLeadName" class="control-label"></label>
<input asp-for="TeamLeadName" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<input asp-for="Description" class="form-control" />
</div>
<div class="form-group">
<label asp-for="GroupMeetingDate" class="control-label"></label>
<input asp-for="GroupMeetingDate" class="form-control" />
</div>
<div class="form-group">
<input type="submit" value="Edit Meeting" class="btn btn-success btn-sm" />
</div>
</form>
</div>
<div class="col-md-8">
</div>
</div>
<div>
<a asp-action="Index">Back To Home</a>
</div>
Click on "Edit" button on index view page as follow
It will open the following page when you click on the "edit" button. Then the group meeting will get updated into the database and redirect to the index view page.
Change the group meeting detail as per your requirement and click on "Edit Meeting" button to update the group meeting details. It will update the group meeting detail and redirect to the home page.
Step 19:
We will create “DeleteMeeting” view in the GroupMeeting Controller and write the code to delete the group meeting detail as follow.
There are two views of DeleteMeeting "HttpGet" and "HttpPost" as follow.
[HttpGet]
public IActionResult DeleteMeeting(int id)
{
GroupMeeting group = GroupMeeting.GetGroupMeetingById(id);
if (group == null)
{
return NotFound();
}
return View(group);
}
[HttpPost]
public IActionResult DeleteMeeting(int id, GroupMeeting groupMeeting)
{
if (GroupMeeting.DeleteGroupMeeting(id) > 0)
{
return RedirectToAction("Index");
}
return View(groupMeeting);
}
Step 20:
Write the “DeleteMeeting.cshtml” view page code as follow.
@model GroupMeetingASP.NETCoreWebApp.Models.GroupMeeting
@{
ViewData["Title"] = "DeleteMeeting";
}
<h3 class="alert">Are you sure you want to delete this?</h3>
<div>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.ProjectName)
</dt>
<dd>
@Html.DisplayFor(model => model.ProjectName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.GroupMeetingLeadName)
</dt>
<dd>
@Html.DisplayFor(model => model.GroupMeetingLeadName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.TeamLeadName)
</dt>
<dd>
@Html.DisplayFor(model => model.TeamLeadName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Description)
</dt>
<dd>
@Html.DisplayFor(model => model.Description)
</dd>
<dt>
@Html.DisplayNameFor(model => model.GroupMeetingDate)
</dt>
<dd>
@Html.DisplayFor(model => model.GroupMeetingDate)
</dd>
</dl>
<form asp-action="DeleteMeeting">
<input type="hidden" asp-for="Id" />
<input type="submit" value="YES" class="btn btn-danger btn-sm" /> <a asp-action="Index" class="btn btn-danger">NO</a>
</form>
</div>
Run the application the default index view page, will get open Then click on delete link as follow.
After click on “delete” button on the index view page, the following page will get open for confirmation to delete the group meeting.
After that click on “Yes” button, the selected group meeting will get deleted from the list of group meeting and the page will redirect to the index view page and the page will look likes as follow.
I hope you understand the CRUD operation in ASP.NET Core with Razor view pages using Dapper ORM.If you like this article please add your valuable comment and share this article.
Reference:
Thanks for reading.
Great Article.. Thanks for sharing.
ReplyDeleteThank you so much Narayan...........
ReplyDeleteI am facing some errors would you please help me
ReplyDeleteYes sure, Please share you error.
ReplyDeleteGood introduction. Few errors. Can you help?
ReplyDeleteYes, Please share your error detail.
DeleteDropdown list
ReplyDeleteRequirement
Dropdown list/s - required in several Views
How to write a generic function in C#, MVC4 , Dapper ORM
something like sp_ddl('City')
/*
DB procedure
CREATE Proc [dbo].[spm_common] as
BEGIN
select description from m_common order by description
END
Table data
Code Description
City Delhi
City Chennai
City Bangalore
Currency U.S.D
Currency INR
Currency AED
Designation Manager
Designation Director
Designation V.P
*/
/*
View-1
In view something like
@Html.DropDownList('Currency')
@Html.DropDownList('Designation')
*/
/*
View-2
In view something like
@Html.DropDownList('Currency')
@Html.DropDownList('Designation')
*/
/*
View-3
In view something like
@Html.DropDownList('Designation')
*/
Enviornment
MS SQL
Visualstudio 2019
MVC core - Database first
Hello mmate nice post
ReplyDelete