Using NPoco ORM In ASP.NET Core

Introduction

As you know, we have so many ORMs available, such as NHibernate, Entity Framework, Dapper.Net which are used to communicate with the database in order to perform CRUD (Create, Read, Update, Delete), and also retrieve data based on criteria.

In this article, we will learn how we can use NPoco ORM (Object Relational Mapping) to perform CRUD operations. So, let’s discover this simple ORM step by step. I hope you will like it.

Prerequisites

Make sure you have installed Visual Studio 2017 (.Net Framework 4.6.1) and SQL Server.

In this post, we are going to:

  • Create application.
  • Install NPoco ORM.
  • Create Customer controller.
  • Do a demo

SQL Database part

Here, you will  find the scripts to create the database and table.

Create Database

  1. USE [master]  
  2. GO  
  3.   
  4. /****** Object:  Database [DbCustomers]    Script Date: 2/25/2018 7:45:46 AM ******/  
  5. CREATE DATABASE [DbCustomers]  
  6.  CONTAINMENT = NONE  
  7.  ON  PRIMARY   
  8. NAME = N'DbCustomers', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbCustomers.mdf' , SIZE = 4096KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  9.  LOG ON   
  10. NAME = N'DbCustomers_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbCustomers_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  11. GO  
  12.   
  13. ALTER DATABASE [DbCustomers] SET COMPATIBILITY_LEVEL = 110  
  14. GO  
  15.   
  16. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  17. begin  
  18. EXEC [DbCustomers].[dbo].[sp_fulltext_database] @action = 'enable'  
  19. end  
  20. GO  
  21.   
  22. ALTER DATABASE [DbCustomers] SET ANSI_NULL_DEFAULT OFF   
  23. GO  
  24.   
  25. ALTER DATABASE [DbCustomers] SET ANSI_NULLS OFF   
  26. GO  
  27.   
  28. ALTER DATABASE [DbCustomers] SET ANSI_PADDING OFF   
  29. GO  
  30.   
  31. ALTER DATABASE [DbCustomers] SET ANSI_WARNINGS OFF   
  32. GO  
  33.   
  34. ALTER DATABASE [DbCustomers] SET ARITHABORT OFF   
  35. GO  
  36.   
  37. ALTER DATABASE [DbCustomers] SET AUTO_CLOSE OFF   
  38. GO  
  39.   
  40. ALTER DATABASE [DbCustomers] SET AUTO_CREATE_STATISTICS ON   
  41. GO  
  42.   
  43. ALTER DATABASE [DbCustomers] SET AUTO_SHRINK OFF   
  44. GO  
  45.   
  46. ALTER DATABASE [DbCustomers] SET AUTO_UPDATE_STATISTICS ON   
  47. GO  
  48.   
  49. ALTER DATABASE [DbCustomers] SET CURSOR_CLOSE_ON_COMMIT OFF   
  50. GO  
  51.   
  52. ALTER DATABASE [DbCustomers] SET CURSOR_DEFAULT  GLOBAL   
  53. GO  
  54.   
  55. ALTER DATABASE [DbCustomers] SET CONCAT_NULL_YIELDS_NULL OFF   
  56. GO  
  57.   
  58. ALTER DATABASE [DbCustomers] SET NUMERIC_ROUNDABORT OFF   
  59. GO  
  60.   
  61. ALTER DATABASE [DbCustomers] SET QUOTED_IDENTIFIER OFF   
  62. GO  
  63.   
  64. ALTER DATABASE [DbCustomers] SET RECURSIVE_TRIGGERS OFF   
  65. GO  
  66.   
  67. ALTER DATABASE [DbCustomers] SET  DISABLE_BROKER   
  68. GO  
  69.   
  70. ALTER DATABASE [DbCustomers] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  71. GO  
  72.   
  73. ALTER DATABASE [DbCustomers] SET DATE_CORRELATION_OPTIMIZATION OFF   
  74. GO  
  75.   
  76. ALTER DATABASE [DbCustomers] SET TRUSTWORTHY OFF   
  77. GO  
  78.   
  79. ALTER DATABASE [DbCustomers] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  80. GO  
  81.   
  82. ALTER DATABASE [DbCustomers] SET PARAMETERIZATION SIMPLE   
  83. GO  
  84.   
  85. ALTER DATABASE [DbCustomers] SET READ_COMMITTED_SNAPSHOT OFF   
  86. GO  
  87.   
  88. ALTER DATABASE [DbCustomers] SET HONOR_BROKER_PRIORITY OFF   
  89. GO  
  90.   
  91. ALTER DATABASE [DbCustomers] SET RECOVERY SIMPLE   
  92. GO  
  93.   
  94. ALTER DATABASE [DbCustomers] SET  MULTI_USER   
  95. GO  
  96.   
  97. ALTER DATABASE [DbCustomers] SET PAGE_VERIFY CHECKSUM    
  98. GO  
  99.   
  100. ALTER DATABASE [DbCustomers] SET DB_CHAINING OFF   
  101. GO  
  102.   
  103. ALTER DATABASE [DbCustomers] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  104. GO  
  105.   
  106. ALTER DATABASE [DbCustomers] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  107. GO  
  108.   
  109. ALTER DATABASE [DbCustomers] SET  READ_WRITE   
  110. GO  

Create Table

After creating the database, we will move on to creating the customers table.

Customers Table

  1. USE [DbCustomers]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Customers]    Script Date: 2/25/2018 7:46:32 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[Customers](  
  15.     [CustomerID] [int] IDENTITY(1,1) NOT NULL,  
  16.     [CustomerName] [varchar](50) NULL,  
  17.     [CustomerEmail] [varchar](50) NULL,  
  18.     [CustomerCountry] [varchar](50) NULL,  
  19.  CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED   
  20. (  
  21.     [CustomerID] ASC  
  22. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  23. ON [PRIMARY]  
  24.   
  25. GO  
  26.   
  27. SET ANSI_PADDING OFF  
  28. GO                                                       

Create application

Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select ASP.NET Core Web Application, name your project, and click OK.

ASP.NET Core

Next, a new dialog will pop up for selecting the template. We are going choose Web API template and click Ok.

ASP.NET Core

Once our project is created, the next step is to install NPoco ORM.

Installing NPoco ORM

In solution explorer, right click on References >> Manage NuGet Packages.

Now, type NPoco in search input and then click on Install button.

ASP.NET Core

After that, we need to create Customer Model that is used to map results.

Customer.cs

  1. using NPoco;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace NPocoApp.Models  
  8. {  
  9.     [TableName("Customers")]  
  10.     [PrimaryKey("CustomerID")]  
  11.     public class Customer  
  12.     {  
  13.         public int CustomerId { get; set; }  
  14.         public string CustomerName { get; set; }  
  15.         public string CustomerEmail { get; set; }  
  16.         public string CustomerCountry { get; set; }  
  17.     }  
  18. }  

Now, we are creating ICustomerRepository interface.

To do that, right-click on project name >> Add >> New Item >> Selecting Interface.

ICustomerRepository.cs

  1. using NPocoApp.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace NPocoApp  
  8. {  
  9.     public interface ICustomerRepository  
  10.     {  
  11.         IList<Customer> GetAllCustomers();  
  12.         Customer GetCustomerById(int idCustomer);  
  13.         void AddCustomer(Customer customer);  
  14.         void UpdateCustomer(int id, Customer customer);  
  15.         void DelecteCustomer(int idCustomer);  
  16.     }  
  17. }   

Next, we will add CustomerRepository class which implements ICustomerRepository interface.

CustomerRepository.cs

  1. using NPoco;  
  2. using NPocoApp.Models;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Data.SqlClient;  
  6. using System.Linq;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace NPocoApp  
  10. {  
  11.     public class CustomerRepository : ICustomerRepository  
  12.     {  
  13.         //Connection Object  
  14.         IDatabase connection = new Database(@"Data Source=.;Initial Catalog=DbCustomers;Integrated Security=True;", DatabaseType.SqlServer2012, SqlClientFactory.Instance);  
  15.   
  16.         public IList<Customer> GetAllCustomers()  
  17.         {  
  18.             string query = "SELECT * FROM Customers";  
  19.             IList<Customer> customerList = connection.Fetch<Customer>(query);  
  20.   
  21.             return customerList;  
  22.         }  
  23.   
  24.         public Customer GetCustomerById(int idCustomer)  
  25.         {  
  26.             Customer customer = connection.SingleById<Customer>(idCustomer);  
  27.             return customer;  
  28.         }  
  29.   
  30.         public void AddCustomer(Customer customer)  
  31.         {  
  32.             connection.Insert<Customer>(customer);  
  33.         }  
  34.   
  35.         public void UpdateCustomer(int id, Customer customer)  
  36.         {  
  37.             customer.CustomerId = id;  
  38.             connection.Update(customer);  
  39.         }  
  40.   
  41.         public void DelecteCustomer(int idCustomer)  
  42.         {  
  43.             connection.Delete<Customer>(idCustomer);  
  44.         }  
  45.   
  46.     }  
  47. }  

As you can see, we created connection object by using Database class which accepts a connection string, database type, and database provider. After that, we proceeded to perform CRUD operations. Note that IDatabase provides all necessary methods to perform CRUD operations.

I’d like to point out, NPoco works by mapping the column names to the property names on the customer object. This is a case insensitive match.

By default no mapping is required. It will be assumed that the table name will be the class name and primary key will be ‘id’. If its not specified, we can use the attributes which are offered by NPoco ORM.

Create a controller

Now, we are going to create a controller. Right click on the controllers folder> > Add >> Controller>> selecting API Controller – Empty >> click Add. In the next dialog, name the controller as CustomerController and then click Add.

ASP.NET Core

ASP.NET Core

CustomerController.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Http;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. using NPocoApp.Models;  
  8.   
  9. namespace NPocoApp.Controllers  
  10. {  
  11.     [Produces("application/json")]  
  12.     [Route("api/Customer")]  
  13.     public class CustomerController : Controller  
  14.     {  
  15.   
  16.         private readonly ICustomerRepository _customerRepository = new CustomerRepository();  
  17.   
  18.         public IList<Customer> GetCustomers()  
  19.         {  
  20.             return _customerRepository.GetAllCustomers();  
  21.         }  
  22.   
  23.         [HttpGet("{id}")]  
  24.         public Customer GetCustomerById(int id)  
  25.         {  
  26.             return _customerRepository.GetCustomerById(id);  
  27.         }  
  28.   
  29.         [HttpPost]  
  30.         public void AddCustomer([FromBody]Customer customer)  
  31.         {  
  32.             _customerRepository.AddCustomer(customer);  
  33.         }  
  34.   
  35.         [HttpPut("{id}")]  
  36.         public void UpdateCustomer(int id, [FromBody]Customer customer)  
  37.         {  
  38.             _customerRepository.UpdateCustomer(id, customer);  
  39.         }  
  40.   
  41.         [HttpDelete("{id}")]  
  42.         public void DeleteCustomer(int id)  
  43.         {  
  44.             _customerRepository.DelecteCustomer(id);  
  45.         }  
  46.   
  47.   
  48.   
  49.     }  
  50. }  

Demo

Now, we are ready. We can run and test our API. Note, I used the Fiddler tool in order to test CRUD operations.

As you can see below, GetCustomers method returns all data rows from customers table.

ASP.NET Core

Here, GetCustomerById method gets customer object based on the provided id parameter.

ASP.NET Core

Now, we will test AddCustomer method which accepts customer object as parameter and insert it into customers table.

ASP.NET Core

When we refresh customers table, we can see that customer data has been inserted successfully.

ASP.NET Core

Here, UpdateCustomer method is used to update customer data.

ASP.NET Core

When we refresh customers table, we can see that customer has been updated successfully.

ASP.NET Core

Finally, we have DeleteCustomer method which is used to delete customer data.

ASP.NET Core

When we refresh customers table, we can see that customer has been deleted successfully.

ASP.NET Core

That’s all. Please leave your feedback and queries in the comments box.