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
Create Table
After creating the database, we will move on to creating the customers table.
Customers Table
- USE [DbCustomers]
- GO
-
- /****** Object: Table [dbo].[Customers] Script Date: 2/25/2018 7:46:32 AM ******/
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- SET ANSI_PADDING ON
- GO
-
- CREATE TABLE [dbo].[Customers](
- [CustomerID] [int] IDENTITY(1,1) NOT NULL,
- [CustomerName] [varchar](50) NULL,
- [CustomerEmail] [varchar](50) NULL,
- [CustomerCountry] [varchar](50) NULL,
- CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
- (
- [CustomerID] 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
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.
Next, a new dialog will pop up for selecting the template. We are going choose Web API template and click Ok.
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.
After that, we need to create Customer Model that is used to map results.
Customer.cs
- using NPoco;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace NPocoApp.Models
- {
- [TableName("Customers")]
- [PrimaryKey("CustomerID")]
- public class Customer
- {
- public int CustomerId { get; set; }
- public string CustomerName { get; set; }
- public string CustomerEmail { get; set; }
- public string CustomerCountry { get; set; }
- }
- }
Now, we are creating ICustomerRepository interface.
To do that, right-click on project name >> Add >> New Item >> Selecting Interface.
ICustomerRepository.cs
- using NPocoApp.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace NPocoApp
- {
- public interface ICustomerRepository
- {
- IList<Customer> GetAllCustomers();
- Customer GetCustomerById(int idCustomer);
- void AddCustomer(Customer customer);
- void UpdateCustomer(int id, Customer customer);
- void DelecteCustomer(int idCustomer);
- }
- }
Next, we will add CustomerRepository class which implements ICustomerRepository interface.
CustomerRepository.cs
- using NPoco;
- using NPocoApp.Models;
- using System;
- using System.Collections.Generic;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace NPocoApp
- {
- public class CustomerRepository : ICustomerRepository
- {
-
- IDatabase connection = new Database(@"Data Source=.;Initial Catalog=DbCustomers;Integrated Security=True;", DatabaseType.SqlServer2012, SqlClientFactory.Instance);
-
- public IList<Customer> GetAllCustomers()
- {
- string query = "SELECT * FROM Customers";
- IList<Customer> customerList = connection.Fetch<Customer>(query);
-
- return customerList;
- }
-
- public Customer GetCustomerById(int idCustomer)
- {
- Customer customer = connection.SingleById<Customer>(idCustomer);
- return customer;
- }
-
- public void AddCustomer(Customer customer)
- {
- connection.Insert<Customer>(customer);
- }
-
- public void UpdateCustomer(int id, Customer customer)
- {
- customer.CustomerId = id;
- connection.Update(customer);
- }
-
- public void DelecteCustomer(int idCustomer)
- {
- connection.Delete<Customer>(idCustomer);
- }
-
- }
- }
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.
CustomerController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using NPocoApp.Models;
-
- namespace NPocoApp.Controllers
- {
- [Produces("application/json")]
- [Route("api/Customer")]
- public class CustomerController : Controller
- {
-
- private readonly ICustomerRepository _customerRepository = new CustomerRepository();
-
- public IList<Customer> GetCustomers()
- {
- return _customerRepository.GetAllCustomers();
- }
-
- [HttpGet("{id}")]
- public Customer GetCustomerById(int id)
- {
- return _customerRepository.GetCustomerById(id);
- }
-
- [HttpPost]
- public void AddCustomer([FromBody]Customer customer)
- {
- _customerRepository.AddCustomer(customer);
- }
-
- [HttpPut("{id}")]
- public void UpdateCustomer(int id, [FromBody]Customer customer)
- {
- _customerRepository.UpdateCustomer(id, customer);
- }
-
- [HttpDelete("{id}")]
- public void DeleteCustomer(int id)
- {
- _customerRepository.DelecteCustomer(id);
- }
-
-
-
- }
- }
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.
Here, GetCustomerById method gets customer object based on the provided id parameter.
Now, we will test AddCustomer method which accepts customer object as parameter and insert it into customers table.
When we refresh customers table, we can see that customer data has been inserted successfully.
Here, UpdateCustomer method is used to update customer data.
When we refresh customers table, we can see that customer has been updated successfully.
Finally, we have DeleteCustomer method which is used to delete customer data.
When we refresh customers table, we can see that customer has been deleted successfully.
That’s all. Please leave your feedback and queries in the comments box.