ASP.NET Core Web API With Dapper And VS 2017

ASP.NET

I will create an ASP.NET Core Web API from scratch, using Visual Studio 2017 ,and you can follow along or skip some steps, if you are already aware of how to create ASP.NET Core Web API.

I will start from a very basic concept and then go to the advanced concepts. In this project, I will be using 3 layers: API Layer, Business Layer, and Repository Layer, and some separate projects for the entities, then I will use Dapper at the Repository Layer as Micro ORM. I will show you how to add assembly (*.DLL) references in .NET Core API and how to add .NET Core Class Library (.NET Standard). I will also discuss about skipping Business Layer and directly calling Repository Layer class from Web API Layer and using Generic Repository interface.

I am going to use Visual Studio 2017 RC and IDE, but you can also use Visual Studio 2015 as IDE. If you didn’t have the template for ASP.NET Core, you need to install this template.

Step 1

Create ASP.NET Core Web API Project
  1. Open “Visual Studio 2017” -> go to “File” menu -> New -> Project

    Or

    Press “Ctrl + Shift + N” after opening Visual Studio Application

  2. Select project template.

    ASP.NET

    Select the project template, as displayed in the preceding screenshot and click OK to continue. Here, I am selecting ASP.NET Core Web Application with .NET Core Framework because I would like to create a project, which can run on multiple operating systems including Windows, Mac and Linux.

  3. Select a template from ASP.NET Core templates.

    ASP.NET

Please select the “Web API” template from ASP.NET Core templates list. Right now, I would like to focus only on Web API and Dapper, so I would recommend that you do not select any authentication and also enable Docker Support. In the next article, I will explain how can we enable Docker support and Authentication mechanism. Preceding is the screenshot for the same.

After selecting “Web API” template from ASP.NET Core templates list, click OK to continue. Visual Studio will create a sample Web API Service for you.

ASP.NET

As you can see in the preceding screenshot it has added a default controller. “ValuesController.cs”. You can delete this file later on because I am not going to use this default controller but right now, this file is useful for us and we can at least test whether our web application is running or not.

Step 2

Checking if Web API service is running fine.

Just press F5 or Ctrl+F5 and you will find that it will open a Web API URL in a new Browser Window.

ASP.NET

As you can see in the preceding screenshot, it has taken a URL and also displayed some values in the browser.

If you look closely at the Visual Studio Run button, then you will find that there is one more option available apart from IIS hosting and it is self-hosting. Following is the screenshot for the same for your reference.

ASP.NET

You may have noticed that the base class (parent controller) for “ValuesController” is different than the earlier versions of Web API. Because in ASP.NET Core Framework, ASP.NET MVC & ASP.NET Web API has been merged and both have the parent controller as Controller (Microsoft.AspNetCore.Mvc.Controller).

ASP.NET

Step 3  
 
Add Business logic project for Web API.

Right click on Solution Explorer -> Add -> New Project. 

ASP.NET

Expand the installed template and select .NET Core and inside it, select Class Library (.NET Standard).

.NET standard library is a formal specification of .NET APIs, which are intended to be available on all .NET runtimes. The motivation behind the standard library is establishing greater uniformity in the .NET ecosystem. You can read more about .NET standard library here .

Give the project name “DataManagement.Business” and press OK to continue. Afterwards, Visual Studio will add a new project of type “.NET Standard Library”.

Step 4
 
Add Business Layer project for the interfaces.

Repeat the same step mentioned in step 3 and add a project with the name “DataManagement.Business.Interfaces” of type “.NET Standard Library”.

Step 5
 
Add Repository Layer project for interfaces.

Repeat the same step mentioned in step 3 and add a project with the name “DataManagement.Repository.Interfaces” of type “.NET Standard Library”.

Step 6
 
Add Repository Layer project for classes.

Repeat the same step mentioned in step 3 and add a project with the name “DataManagement.Repository” of type “.NET Standard Library”.

Step 7
 
Add a project for Entities

Repeat the same step mentioned in step 3 and add a project with the name “DataManagement.Entities” of type “.NET Standard Library”.

After adding all the projects mentioned above, your Solution Explorer will look  as shown below in the screenshot.



Step 8
 
Create database, table & stored procedure for CRUD operation

SQL Script

Script 1
 
Script to create database
  1. createdatabase DataManagement  
Script 2
 
Script to create table
  1. CREATETABLE[dbo].[Users](  
  2.     [UserId][int] IDENTITY(1, 1) NOT NULL, [UserName][varchar](50) NULL, [UserMobile][varchar](50) NULL, [UserEmail][varchar](50) NULL, [FaceBookUrl][varchar](50) NULL, [LinkedInUrl][varchar](50) NULL, [TwitterUrl][varchar](50) NULL, [PersonalWebUrl][varchar](50) NULL, [IsDeleted][bit] NULL) ON[PRIMARY]  
  3. GO  
  4. ALTERTABLE[dbo].[Users] ADDCONSTRAINT[DF_User_IsDeleted] DEFAULT((0)) FOR[IsDeleted]  
  5. GO  
Script 3
 
Script to add user
  1. createPROCEDURE[dbo].[AddUser]  
  2. @UserName varchar(50),  
  3.     @UserMobile varchar(50),  
  4.     @UserEmail varchar(50),  
  5.     @FaceBookUrl varchar(50),  
  6.     @LinkedInUrl varchar(50),  
  7.     @TwitterUrl varchar(50),  
  8.     @PersonalWebUrl varchar(50)  
  9. AS  
  10. BEGIN  
  11. SETNOCOUNTON;  
  12. insertinto Users(UserName, UserMobile, UserEmail, FaceBookUrl, LinkedInUrl, TwitterUrl, PersonalWebUrl)  
  13. values(@UserName, @UserMobile, @UserEmail, @FaceBookUrl, @LinkedInUrl, @TwitterUrl, @PersonalWebUrl)  
  14. END  
  15. GO  
Script 4
 
Script to delete user
  1. CREATEPROCEDURE[dbo].[DeleteUser]  
  2. @UserId int  
  3. AS  
  4. BEGIN  
  5. SETNOCOUNTON;  
  6. update Users set IsDeleted = 1 where UserId = @UserId  
  7. END  
  8. Script 5 Script to get all users  
  9. CREATEPROCEDURE[dbo].[GetAllUsers]  
  10. AS  
  11. BEGIN  
  12. SETNOCOUNTON;  
  13. select * from Users  
  14. END  
Script 6
 
Script to get user by Id
  1. CREATEPROCEDURE[dbo].[GetUserById]  
  2. @UserId int  
  3. AS  
  4. BEGIN  
  5. SETNOCOUNTON;  
  6. select * from Users where UserId = @UserId;  
  7. END  
  8. GO  
Script 7
 
Script to update user
  1. CREATEPROCEDURE[dbo].[UpdateUser]  
  2. @UserId int,  
  3. @UserName varchar(50),  
  4.     @UserMobile varchar(50),  
  5.     @UserEmail varchar(50),  
  6.     @FaceBookUrl varchar(50),  
  7.     @LinkedInUrl varchar(50),  
  8.     @TwitterUrl varchar(50),  
  9.     @PersonalWebUrl varchar(50)  
  10. AS  
  11. BEGIN  
  12. SETNOCOUNTON;  
  13. update Users set  
  14. UserName = @UserName,  
  15.     UserMobile = @UserMobile,  
  16.     UserEmail = @UserEmail,  
  17.     FaceBookUrl = @FaceBookUrl,  
  18.     LinkedInUrl = @LinkedInUrl,  
  19.     TwitterUrl = @TwitterUrl,  
  20.     PersonalWebUrl = @PersonalWebUrl  
  21. where UserId = @UserId  
  22. END  
  23. GO  
Step 9
 
Add an Entity for User
  1. Create a class“ User.cs” inside“ DataManagement.Entities” project.  
  2. Complete Code  
  3. namespace DataManagement.Entities {  
  4.     publicclassUser {  
  5.         publicint UserId {  
  6.             get;  
  7.             set;  
  8.         }  
  9.         publicstring UserName {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         publicstring UserMobile {  
  14.             get;  
  15.             set;  
  16.         }  
  17.         publicstring UserEmail {  
  18.             get;  
  19.             set;  
  20.         }  
  21.         publicstring FaceBookUrl {  
  22.             get;  
  23.             set;  
  24.         }  
  25.         publicstring LinkedInUrl {  
  26.             get;  
  27.             set;  
  28.         }  
  29.         publicstring TwitterUrl {  
  30.             get;  
  31.             set;  
  32.         }  
  33.         publicstring PersonalWebUrl {  
  34.             get;  
  35.             set;  
  36.         }  
  37.         publicbool IsDeleted {  
  38.             get;  
  39.             set;  
  40.         }  
  41.     }  
  42. }  
Step 10
 
Write Repository Layer Code for User
  1. Add reference of project “DataManagement.Entities”inside “DataManagement.Repository.Interfaces”.

    For ASP.NET Core you will find it a little bit different as compared to earlier versions while checking for added references. Following is a snapshot for the same.

    Entities

  2. Create an Interface “IUserRepository.cs” inside the solution “DataManagement.Repository.Interfaces”.
    1. IUserRepository.cs Complete Code  
    2. using DataManagement.Entities;  
    3. using System.Collections.Generic;  
    4. namespace DataManagement.Repository.Interfaces {  
    5.     publicinterfaceIUserRepository {  
    6.         bool AddUser(User user);  
    7.         bool UpdateUser(User user);  
    8.         bool DeleteUser(int userId);  
    9.         IList < User > GetAllUser();  
    10.         User GetUserById(int userId);  
    11.     }  
    12. }  
  3. Add reference of projects

    “DataManagement.Entities”&“DataManagement.Repository.Interfaces” inside “DataManagement.Repository”.

  4. Create a class“BaseRepository.cs” inside the project“DataManagement.Repository”.
    1. using System;  
    2. using System.Data;  
    3. using System.Data.SqlClient;  
    4. namespace DataManagement.Repository {  
    5.     publicclassBaseRepository IDisposable {  
    6.         protectedIDbConnection con;  
    7.         public BaseRepository() {  
    8.             string connectionString = "Data Source=****;Initial Catalog=DataManagement;Integrated Security=True";  
    9.             con = newSqlConnection(connectionString);  
    10.         }  
    11.         publicvoid Dispose() {  
    12.             //throw new NotImplementedException();  
    13.         }  
    14.     }  
    15. }  
  5. Install some packages from NuGet Package manager.

    Entities

    In the preceding screenshot, you can see that at Repository Layer is displaying that 4 packages have been installed from NuGet Package Manager. The project “DataManagement.Repository” is of .NET Core Class Library(.NET Standard) refers to the screenshot of step 3 for .NET Standard library.

    As “DataManagement.Repository” is .NET standard library, so you will find that NuGet package “NETStandard.Library” is installed already, but you will require to install 3 other packages.

    1. System.Data.SqlClient

      System.Data.SqlClient is NuGet Package from Microsoft. I have installed this package, because I am including “System.Data” & “System.Data.SqlClient” in using block.

      I would like to clarify that whatever packages we need for ASP.NET Core Cross Platform Application, we will have to install them from NuGet Package Manager and you will not find any installed DLL on the machine for the same. The screenshot is given below to display the message that “No Framework assemblies were found on the machine.”

      Entities

    2. System.Runtime
       
      System.Runtime is also a NuGet Package from Microsoft. I have used “IDisposable” interface for which I need to install “System.Runtime”.

    3. Dapper
       
      Dapper is a high performance Micro-ORM. As stated earlier, I am not using Entity Framework in this project, as I am using Dapper instead.

  6. Create a class“UserRepository.cs” inside the project “DataManagement.Repository”.
    1. using Dapper;  
    2. using DataManagement.Entities;  
    3. using System;  
    4. using System.Collections.Generic;  
    5. using System.Data.SqlClient;  
    6. using System.Linq;  
    7. usingstatic System.Data.CommandType;  
    8. using DataManagement.Repository.Interfaces;  
    9. namespace DataManagement.Repository {  
    10.     publicclassUserRepositoryBaseRepository,  
    11.     IUserRepository {  
    12.         publicbool AddUser(User user) {  
    13.             try {  
    14.                 DynamicParameters parameters = newDynamicParameters();  
    15.                 parameters.Add("@UserName", user.UserName);  
    16.                 parameters.Add("@UserMobile", user.UserMobile);  
    17.                 parameters.Add("@UserEmail", user.UserEmail);  
    18.                 parameters.Add("@FaceBookUrl", user.FaceBookUrl);  
    19.                 parameters.Add("@LinkedInUrl", user.LinkedInUrl);  
    20.                 parameters.Add("@TwitterUrl", user.TwitterUrl);  
    21.                 parameters.Add("@PersonalWebUrl", user.PersonalWebUrl);  
    22.                 SqlMapper.Execute(con, "AddUser", param parameters, commandType StoredProcedure);  
    23.                 returntrue;  
    24.             } catch (Exception ex) {  
    25.                 throw ex;  
    26.             }  
    27.         }  
    28.         publicbool DeleteUser(int userId) {  
    29.             DynamicParameters parameters = newDynamicParameters();  
    30.             parameters.Add("@UserId", userId);  
    31.             SqlMapper.Execute(con, "DeleteUser", param parameters, commandType StoredProcedure);  
    32.             returntrue;  
    33.         }  
    34.         publicIList < User > GetAllUser() {  
    35.             IList < User > customerList = SqlMapper.Query < User > (con, "GetAllUsers", commandType StoredProcedure).ToList();  
    36.             return customerList;  
    37.         }  
    38.         publicUser GetUserById(int userId) {  
    39.             try {  
    40.                 DynamicParameters parameters = newDynamicParameters();  
    41.                 parameters.Add("@CustomerID", userId);  
    42.                 returnSqlMapper.Query < User > ((SqlConnection) con, "GetUserById", parameters, commandType StoredProcedure).FirstOrDefault();  
    43.             } catch (Exception) {  
    44.                 throw;  
    45.             }  
    46.         }  
    47.         publicbool UpdateUser(User user) {  
    48.             try {  
    49.                 DynamicParameters parameters = newDynamicParameters();  
    50.                 parameters.Add("@UserId", user.UserId);  
    51.                 parameters.Add("@UserName", user.UserName);  
    52.                 parameters.Add("@UserMobile", user.UserMobile);  
    53.                 parameters.Add("@UserEmail", user.UserEmail);  
    54.                 parameters.Add("@FaceBookUrl", user.FaceBookUrl);  
    55.                 parameters.Add("@LinkedInUrl", user.LinkedInUrl);  
    56.                 parameters.Add("@TwitterUrl", user.TwitterUrl);  
    57.                 parameters.Add("@PersonalWebUrl", user.PersonalWebUrl);  
    58.                 SqlMapper.Execute(con, "UpdateUser", param parameters, commandType StoredProcedure);  
    59.                 returntrue;  
    60.             } catch (Exception ex) {  
    61.                 throw ex;  
    62.             }  
    63.         }  
    64.     }  
    65. }  

Step 11

Write Business Layer Code for User
  1. Add the project reference for “DataManagement.Entities” inside “DataManagement.Business.Interfaces”.

  2. Add an interface “IUserManager.cs”inside .NET Standard Class Library “DataManagement.Business.Interfaces”.

    IUserManager.csComplete Code
    1. using DataManagement.Entities;  
    2. using System.Collections.Generic;  
    3. namespace DataManagement.Business.Interfaces {  
    4.     publicinterfaceIUserManager {  
    5.         bool AddUser(User user);  
    6.         bool UpdateUser(User user);  
    7.         bool DeleteUser(int userId);  
    8.         IList < User > GetAllUser();  
    9.         User GetUserById(int userId);  
    10.     }  
    11. }  
  3. Add project reference of “DataManagement.Entities”, “DataManagement.Business.Interfaces”&“DataManagement.Repository.Interfaces” inside “DataManagement.Business”.

  4. Add a class “UserManager.cs” inside the .NET Standard Class Library “DataManagement.Business”

    UserManager.cs Complete Code
    1. using DataManagement.Business.Interfaces;  
    2. using DataManagement.Entities;  
    3. using DataManagement.Repository.Interfaces;  
    4. using System.Collections.Generic;  
    5. namespace DataManagement.Business {  
    6.     publicclassUserManager IUserManager {  
    7.         IUserRepository _userRepository;  
    8.         public UserManager(IUserRepository userRepository) {  
    9.             _userRepository = userRepository;  
    10.         }  
    11.         publicbool AddUser(User user) {  
    12.             return _userRepository.AddUser(user);  
    13.         }  
    14.         publicbool DeleteUser(int userId) {  
    15.             return _userRepository.DeleteUser(userId);  
    16.         }  
    17.         publicIList < User > GetAllUser() {  
    18.             return _userRepository.GetAllUser();  
    19.         }  
    20.         publicUser GetUserById(int userId) {  
    21.             return _userRepository.GetUserById(userId);  
    22.         }  
    23.         publicbool UpdateUser(User user) {  
    24.             return _userRepository.UpdateUser(user);  
    25.         }  
    26.     }  
    27. }  

Step 12

Write API Layer Code.
  1. Add dependencies and project references.

    Entities

    Add Controller “UserController.cs”.

    Complete code for UserController.cs
    1. using System.Collections.Generic;  
    2. using Microsoft.AspNetCore.Mvc;  
    3. using DataManagement.Business.Interfaces;  
    4. using DataManagement.Entities;  
    5. // For more information on enabling Web API for empty projects, visit https//go.microsoft.com/fwlink/?LinkID=397860  
    6. namespace DataManagement.WebAPI.Controllers {  
    7.     [Route("api/[controller]")]  
    8.     publicclassUserController Controller {  
    9.         IUserManager _userManager;  
    10.         public UserController(IUserManager userManager) {  
    11.             _userManager = userManager;  
    12.         }  
    13.         // GET<td style="border<td style="border: 1px dashed #ababab;"> 1px dashed #ababab;"> api/user  
    14.         [HttpGet]  
    15.         publicIEnumerable < User > Get() {  
    16.             return _userManager.GetAllUser();  
    17.         }  
    18.         // GET api/user/5  
    19.         [HttpGet("{id}")]  
    20.         publicUser Get(int id) {  
    21.             return _userManager.GetUserById(id);  
    22.         }  
    23.         // POST api/user  
    24.         [HttpPost]  
    25.         publicvoid Post([FromBody] User user) {  
    26.             _userManager.AddUser(user);  
    27.         }  
    28.         // PUT api/user/5  
    29.         [HttpPut("{id}")]  
    30.         publicvoid Put(int id, [FromBody] User user) {  
    31.             _userManager.UpdateUser(user);  
    32.         }  
    33.         // DELETE api/user/5  
    34.         [HttpDelete("{id}")]  
    35.         publicvoid Delete(int id) {  
    36.             _userManager.DeleteUser(id);  
    37.         }  
    38.     }  
    39. }  
  2. Add code for dependency injection

    Go to the class startup.cs and inside the method “ConfigureServices(IServiceCollection services)”, add 2 lines of code given below.

    services.AddTransient<IUserManager, UserManager>();
    services.AddTransient<IUserRepository, UserRepository>();

    Entities

    Testing the Web API Service Using Postman.

    Now, our Web API Service is ready. We can test it.

    To test the Service, we can use any Browser, but if we have to send any data in header or have to pass some authentication info then Postman is a very simple tool to test API Services. I am going to use Postman but you can use any other apps also.

    Entities

    As you can see in the screenshot, shown above, the data is being displayed in JSON because JSON format is by default selected in Postman.

    So far, I have just explained how we are going to create a simple Web API Service, using ASP.NET Core.

    Since this application is not an optimized architecture, I have just explained how to create ASP.NET Core Web API Service. Following are some more modifications and optimizations that can be done with this application.

Creating generic repository interface.

Earlier, we have created IUserRepository.cs as repository interface but instead of that, now I am going to create a Generic Repository IRepository.cs.

Complete Code of IRepository.cs

  1. using System.Collections.Generic;  
  2. namespace DataManagement.Repository.Interfaces {  
  3.     publicinterfaceIRepository < T > whereT class {  
  4.         IEnumerable < T > Get();  
  5.         T Get(int id);  
  6.         void Add(T entity);  
  7.         void Delete(int id);  
  8.         void Update(T entity);  
  9.     }  
  10. }  
Now, I am going to add a new Entity Customer in the project “DataManagement.Entities” with the name Customer.cs & also execute some stored procedure for CRUD operation. I am not writing those code snippets here, as those are very simple and you can write it by yourself.

Complete Code of CustomerRepository.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using DataManagement.Repository.Interfaces;  
  5. using DataManagement.Entities;  
  6. using Dapper;  
  7. usingstatic System.Data.CommandType;  
  8. using System.Data.SqlClient;  
  9. namespace DataManagement.Repository {  
  10.     publicclassCustomerRepositoryBaseRepository,  
  11.     IRepository < Customer > {  
  12.         publicvoid Add(Customer entity) {  
  13.             try {  
  14.                 DynamicParameters parameters = newDynamicParameters();  
  15.                 parameters.Add("@CustomerName", entity.CustomerName);  
  16.                 parameters.Add("@CustomerEmail", entity.CustomerEmail);  
  17.                 parameters.Add("@CustomerMobile", entity.CustomerMobile);  
  18.                 SqlMapper.Execute(con, "AddCustomer", param parameters, commandTypeStoredProcedure);  
  19.             } catch (Exception ex) {  
  20.                 throw ex;  
  21.             }  
  22.         }  
  23.         publicvoid Delete(int id) {  
  24.             DynamicParameters parameters = newDynamicParameters();  
  25.             parameters.Add("@CustomerId", id);  
  26.             SqlMapper.Execute(con, "DeleteCustomer", param parameters, commandTypeStoredProcedure);  
  27.         }  
  28.         publicIEnumerable < Customer > Get() {  
  29.             IList < Customer > customerList = SqlMapper.Query < Customer > (con, "GetAllCustomer", commandTypeStoredProcedure).ToList();  
  30.             return customerList;  
  31.         }  
  32.         publicCustomer Get(int id) {  
  33.             DynamicParameters parameters = newDynamicParameters();  
  34.             parameters.Add("@CustomerID", id);  
  35.             returnSqlMapper.Query < Customer > ((SqlConnection) con, "GetCustomerById", parameters, commandTypeStoredProcedure).FirstOrDefault();  
  36.         }  
  37.         publicvoid Update(Customer entity) {  
  38.             DynamicParameters parameters = newDynamicParameters();  
  39.             parameters.Add("@CustomerID", entity.CustomerName);  
  40.             parameters.Add("@CustomerName", entity.CustomerName);  
  41.             parameters.Add("@CustomerEmail", entity.CustomerEmail);  
  42.             parameters.Add("@CustomerMobile", entity.CustomerMobile);  
  43.             SqlMapper.Execute(con, "UpdateCustomer", param parameters, commandType StoredProcedure);  
  44.         }  
  45.     }  
  46. }  
Skipping Business Layer

In the previous example, you have seen that Web API Layer is calling Business Layer and Business Layer was calling Repository layer but if you look closely at the code, you will find that in Business layer I am not doing anything, as I am just calling code of Repository Layer and returning it to Web API Layer.

Thus, if we do not need to write any manipulation logic, we can skip Business Layer. Now, I am directly calling Repository Layer from Web API.

CustomerController class complete code
  1. using System.Collections.Generic;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using DataManagement.Entities;  
  4. using DataManagement.Repository.Interfaces;  
  5. // For more information on enabling Web API for empty projects, visit https//go.microsoft.com/fwlink/?LinkID=397860  
  6. namespace DataManagement.API.Controllers {  
  7.     [Route("api/[controller]")]  
  8.     publicclassCustomerController Controller {  
  9.         IRepository < Customer > _customerRepository;  
  10.         public CustomerController(IRepository < Customer > customerRepository) {  
  11.                 _customerRepository = customerRepository;  
  12.             }  
  13.             [HttpGet]  
  14.         publicIEnumerable < Customer > Get() {  
  15.                 return _customerRepository.Get();  
  16.             }  
  17.             [HttpGet("{id}")]  
  18.         publicCustomer Get(int id) {  
  19.                 return _customerRepository.Get(id);  
  20.             }  
  21.             [HttpPost]  
  22.         publicvoid Post([FromBody] Customer customer) {  
  23.                 _customerRepository.Add(customer);  
  24.             }  
  25.             [HttpPut("{id}")]  
  26.         publicvoid Put(int id, [FromBody] Customer customer) {  
  27.                 _customerRepository.Update(customer);  
  28.             }  
  29.             [HttpDelete("{id}")]  
  30.         publicvoid Delete(int id) {  
  31.             _customerRepository.Delete(id);  
  32.         }  
  33.     }  
  34. }  
Exploring Dapper

So far, we have seen how can we perform CRUD operations very easily using Dapper, but these are the basic things and Dapper can do a lot more.

Entities

Execute a command multiple times with Dapper.
  1. publicvoid InsertMultipleUsers() {  
  2.     object myObj = new [] {  
  3.         new {  
  4.             name = "B Narayan", email = "[email protected]"  
  5.         },  
  6.         new {  
  7.             name = "Manish Sharma", email = "manish.sharma**@outlook.com"  
  8.         },  
  9.         new {  
  10.             name = "Rohit Kumar", email = "rohit.kumar**@outlook.com"  
  11.         }  
  12.     };  
  13.     con.Execute(@ "insert Users(UserName, UserEmail) values (@name, @email)", myObj);  
  14. }  
Mapping executed result to strongly Type List.
  1. publicIList < User > GetAllUser() => SqlMapper.Query < User > (con, "GetAllUsers", commandType StoredProcedure).ToList();  
Mapping executed result to dynamic objects.
  1. publicIList < dynamic > GetAllUser() => SqlMapper.Query < dynamic > (con, "GetAllUsers", commandType StoredProcedure).ToList();  
Execute a command without returning anything
  1. DynamicParameters parameters = newDynamicParameters();  
  2. parameters.Add("@UserId", userId);  
  3. SqlMapper.Execute(con, "DeleteUser", param parameters, commandType StoredProcedure);  
Select Multiple Results
  1. (List < Customer > customers, List < User > users) GetUsersAndCustomers() {  
  2.     using(var multi = con.QueryMultiple("select * from Customers;select * from Users")) {  
  3.         var customers = multi.Read < Customer > ().ToList();  
  4.         var users = multi.Read < User > ().ToList();  
  5.         return (customers, users);  
  6.     }  
  7. }  
Mapping your Columns

Apart from the features mentioned above, you can do many more things with Dapper. If you are thinking that your database column name is different than your C# class object, you can also do mapping of your columns.

Entities

To do Column mapping, you need to add a class ColumnMap.cs
  1. internal class ColumnMap {  
  2.     private readonly Dictionary < string, string > forward = new Dictionary < string, string > ();  
  3.     private readonly Dictionary < string, string > reverse = new Dictionary < string, string > ();  
  4.     public void Add(string t1, string t2) {  
  5.         forward.Add(t1, t2);  
  6.         reverse.Add(t2, t1);  
  7.     }  
  8.     public string this[string index] {  
  9.         get {  
  10.             // Check for a custom column map.  
  11.             if (forward.ContainsKey(index)) return forward[index];  
  12.             if (reverse.ContainsKey(index)) return reverse[index];  
  13.             // If no custom mapping exists, return the value passed in.  
  14.             return index;  
  15.         }  
  16.     }  
  17. }  
In Repository class map it easily. Following the code snippet for the same.
  1. publicIEnumerable < Product > Get() {  
  2.     var columnMap = newColumnMap();  
  3.     columnMap.Add("Id""ProductId");  
  4.     columnMap.Add("Name""ProductName");  
  5.     columnMap.Add("Price""ProductPrice");  
  6.     SqlMapper.SetTypeMap(typeof(Product), newCustomPropertyTypeMap(typeof(Product), (type, columnName) => type.GetProperty(columnMap[columnName])));  
  7.     List < Product > products = SqlMapper.Query < Product > (  
  8.         (SqlConnection) con, "select * from Products", commandTypeText).ToList();  
  9.     return products;  
  10. }  
You can also download NuGet package “Dapper.FluentMap” and it will provide mapping in a more convenient way. You can explore “Dapper.FluentMap” here.

I have attached the complete source code with this article for reference. Sometimes, I have used C# 6 & C# 7 syntax in the code, if you are not aware about C# 7 concepts, you can refer  to the following articles for C# 7.

For C# basic concepts, you can refer to my recent article Basic Interview Tips in C#