In search of code perfection #geek #developer

Getting Started PetaPoco: Create POCO and perform CRUD

I love PetaPoco and I wrote a post about which Micro-ORM is better, I picked PetaPoco and every time I want to access database I use it, it’s fast and easy, no need to setup the mapping like ORMs, but I don’t say that Micro-ORMs are better than ORMs, in some situations you need to use an ORM. PetaPoco is better than using the old ADO.NET approach of using Connection, open it, create either DataTable or DataSet with DataAdapter, and fill them with data.

In this post we’ll learn How to create one POCO and perform CRUD on it, I’ll use the famous Northwind database and create POCO for Customers table, let’s see how we can do it.

If you see message “Successfully installed ‘PetaPoco 4.0.3′.” then you’re ready to go.

Download the whole project from GitHub because PetaPoco is open source project you can download it and you can even add your code if you want, after downloading the project add PetaPoco.cs file to your project.

Create POCO:

Now we’ll create POCO for Customers table in Northwind database, so let’s do it. It’s so simple just create new class and for each column in the table create a property for.

Customer POCO

publicclassCustomer

{

publicstring CustomerID { get; set; }

publicstring CompanyName { get; set; }

publicstring ContactName { get; set; }

publicstring ContactTitle { get; set; }

publicstring Address { get; set; }

publicstring City { get; set; }

publicstring Region { get; set; }

publicstring PostalCode { get; set; }

publicstring Country { get; set; }

publicstring Phone { get; set; }

publicstring Fax { get; set; }

}

Connect To Database:

In order for PetaPoco to your POCOs, you need to have database Connection String in configuration file or construct one in code, so we’ll add App.config file to the project and add a <connectionString> that refer to Northwind database.