.Net C# using the PetaPoco Micro ORM

Micro ORMS are increasingly popular because of their simplicity and generally lower overhead compared to monolithic ORM frameworks. PetaPoco is a commonly used Micro ORM, the code below shows how to get up and running.

1) Create a new project in Visual Studio (2012 in this example).

2) Add thePetaPoco reference to your project, if you’re using nuget from the command line do:

install-package PetaPoco

3) Add a connection string setting to your config file:

<connectionStrings>
    <add name="PetaExample" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Company;Integrated Security=True;Connect Timeout=300;" providerName="System.Data.SqlClient" />
</connectionStrings>

4) Create a new class CsharpPetaPocoDemo.cs with the following contents:

using System;
using System.Linq;
using PetaPoco;

namespace CsharpPetaPocoDemo
{
    /// <summary>
    /// Simple PetaPoco example
    /// </summary>
    class CsharpPetaPocoExample
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            using (var db = new Database("PetaExample"))
            {
                try
                {
                    var result = db.Query<EmployeeInfo>("select * from EmployeeInfo").ToList();

                    result.ForEach(PrintResults);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadKey();
        }

        private static void PrintResults(EmployeeInfo employeeInfo)
        {
            Console.WriteLine("{0} {1} {2} {3} {4}", employeeInfo.EmpNo, employeeInfo.EmpName, employeeInfo.Designation, employeeInfo.DeptName, employeeInfo.Salary);
        }
    }

    /// <summary>
    /// Employee class, using properties for PetaPoco
    /// </summary>
    [TableName("EmployeeInfo")]
    [PrimaryKey("EmpNo")]
    public class EmployeeInfo
    {
        public int EmpNo { get; set; }
        public string EmpName { get; set; }
        public int Salary { get; set; }
        public string DeptName { get; set; }
        public string Designation { get; set; }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *