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:

SQL Database part

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

Create Database

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

Create Table

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

Customers Table

  1. USE [DbCustomers]
  2. GO
  3. /****** Object: Table [dbo].[Customers] Script Date: 2/25/2018 7:46:32 AM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. SET ANSI_PADDING ON
  9. GO
  10. CREATE TABLE [dbo].[Customers](
  11. [CustomerID] [int] IDENTITY(1,1) NOT NULL,
  12. [CustomerName] [varchar](50) NULL,
  13. [CustomerEmail] [varchar](50) NULL,
  14. [CustomerCountry] [varchar](50) NULL,
  15. CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
  16. (
  17. [CustomerID] ASC
  18. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  19. ) ON [PRIMARY]
  20. GO
  21. SET ANSI_PADDING OFF
  22. 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. namespace NPocoApp.Models
  7. {
  8. [TableName("Customers")]
  9. [PrimaryKey("CustomerID")]
  10. public class Customer
  11. {
  12. public int CustomerId { get; set; }
  13. public string CustomerName { get; set; }
  14. public string CustomerEmail { get; set; }
  15. public string CustomerCountry { get; set; }
  16. }
  17. }

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. namespace NPocoApp
  7. {
  8. public interface ICustomerRepository
  9. {
  10. IList<Customer> GetAllCustomers();
  11. Customer GetCustomerById(int idCustomer);
  12. void AddCustomer(Customer customer);
  13. void UpdateCustomer(int id, Customer customer);
  14. void DelecteCustomer(int idCustomer);
  15. }
  16. }

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. namespace NPocoApp
  9. {
  10. public class CustomerRepository : ICustomerRepository
  11. {
  12. //Connection Object
  13. IDatabase connection = new Database(@"Data Source=.;Initial Catalog=DbCustomers;Integrated Security=True;", DatabaseType.SqlServer2012, SqlClientFactory.Instance);
  14. public IList<Customer> GetAllCustomers()
  15. {
  16. string query = "SELECT * FROM Customers";
  17. IList<Customer> customerList = connection.Fetch<Customer>(query);
  18. return customerList;
  19. }
  20. public Customer GetCustomerById(int idCustomer)
  21. {
  22. Customer customer = connection.SingleById<Customer>(idCustomer);
  23. return customer;
  24. }
  25. public void AddCustomer(Customer customer)
  26. {
  27. connection.Insert<Customer>(customer);
  28. }
  29. public void UpdateCustomer(int id, Customer customer)
  30. {
  31. customer.CustomerId = id;
  32. connection.Update(customer);
  33. }
  34. public void DelecteCustomer(int idCustomer)
  35. {
  36. connection.Delete<Customer>(idCustomer);
  37. }
  38. }
  39. }

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. namespace NPocoApp.Controllers
  9. {
  10. [Produces("application/json")]
  11. [Route("api/Customer")]
  12. public class CustomerController : Controller
  13. {
  14. private readonly ICustomerRepository _customerRepository = new CustomerRepository();
  15. public IList<Customer> GetCustomers()
  16. {
  17. return _customerRepository.GetAllCustomers();
  18. }
  19. [HttpGet("{id}")]
  20. public Customer GetCustomerById(int id)
  21. {
  22. return _customerRepository.GetCustomerById(id);
  23. }
  24. [HttpPost]
  25. public void AddCustomer([FromBody]Customer customer)
  26. {
  27. _customerRepository.AddCustomer(customer);
  28. }
  29. [HttpPut("{id}")]
  30. public void UpdateCustomer(int id, [FromBody]Customer customer)
  31. {
  32. _customerRepository.UpdateCustomer(id, customer);
  33. }
  34. [HttpDelete("{id}")]
  35. public void DeleteCustomer(int id)
  36. {
  37. _customerRepository.DelecteCustomer(id);
  38. }
  39. }
  40. }

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.