Use NPoco ORM With ASP.NET Core

NPoco is a simple C# micro-ORM that maps the results of a query onto a POCO object. NPoco is a fork of PetaPoco with a handful of extra features. And NPoco ORM can be used with .NET Core. So in this post, let’s find out how to use NPoco ORM with ASP.NET Core for CRUD operations.

Use NPoco ORM With ASP.NET Core

In this post, we will be using SQL Server as a database with NPoco ORM. So let’s first create the database. Open SQL Server Management Studio and create a new database called “NPocoDemo” or you can name it anything of your choice. And create a table named “Products”.

Okay. Let’s create an ASP.NET Core Web API project. The default Web API template comes with a controller named “Value”. We don’t need this for demo, so I deleted it. To use NPoco ORM, we need to install following nuget package.

NPoco works by mapping the column names to the property names on the entity 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 the primary key will be ‘Id’ if it’s not specified. But when your table name is different from entity name, then you need to use TableName attribute which indicates the table for which the Poco class will be mapped to. Similarly, if primary key column name is other than ‘Id’ then use PrimaryKey attribute to let NPoco know that this is the primary key column for this entity (As decorated in above code).

The only thing is to keep in mind when initializing using DBConnection object, that you will need to open the connection before any DB operation. And while initializing using the connection string, Database class will take care of opening the connection. Please take a look at Database.cs class code in Github and look for _connectionPassedIn property use.

There are CRUD methods defined that uses entity object for all DB operations. As mentioned earlier, in every method

Create IDatabase object.

Pass the object/Query and call the method.

As you can see, there is also a method SingleById to get single record from a table and Fetch method to get all records using a RAW SQL query.

This controller has methods for GET, POST, PUT and DELETE. That’s all to code. Now, let’s just run the application and execute the GET API. Since the table is empty, so you should see following.

Now, let’s add a product via Post API.

And now call the GET Product API again and you should see that product you just added is returned.

Here is the video showing all Product API operations.

That’s it. It’s really very easy to setup and use NPoco. Along with executing SQL queries, you can also use inbuit methods for CRUD operations. And the good thing is that it maps the results to Poco objects. It also supports transaction supports, mapping of nested objects, change tracking, Fluent based mapping and many other features. It’s tiny but really powerful.