CRUD operations with PetaPoco and ASP.NET MVC

  • Home
  • Blog
  • CRUD operations with PetaPoco and ASP.NET MVC

In this post we are going to see how we can do CRUD operations with ASP.NET MVC and PetaPoco Micro ORM. Petapoco is a tiny ORM developed by topten software. As per them it’s a tiny, fast, single-file micro-ORM for .NET and Mono.

  • Like Massive it’s a single file that you easily add to any project
  • Unlike Massive it works with strongly typed POCO’s
  • Like Massive, it now also supports dynamic Expandos too – read more
  • Like ActiveRecord, it supports a close relationship between object and database table
  • Like SubSonic, it supports generation of poco classes with T4 templates
  • Like Dapper, it’s fast because it uses dynamic method generation (MSIL) to assign column values to properties

As per topten software it contains following features.

  • Tiny, no dependencies… a single C# file you can easily add to any project.
  • Works with strictly undecorated POCOs, or attributed almost-POCOs.
  • Helper methods for Insert/Delete/Update/Save and IsNew
  • Paged requests automatically work out total record count and fetch a specific page.
  • Easy transaction support.
  • Better parameter replacement support, including grabbing named parameters from object properties.
  • Great performance by eliminating Linq and fast property assignment with DynamicMethod generation.
  • Includes T4 templates to automatically generate POCO classes for you.
  • The query language is SQL… no weird fluent or Linq syntaxes (yes, matter of opinion)
  • Includes a low friction SQL builder class that makes writing inline SQL much easier.
  • Hooks for logging exceptions, installing value converters and mapping columns to properties without attributes.
  • Works with SQL Server, SQL Server CE, MySQL, PostgreSQL and Oracle.
  • Works under .NET 3.5 or Mono 2.6 and later.
  • Experimental support for dynamic under .NET 4.0 and Mono 2.8
  • NUnit unit tests.
  • OpenSource (Apache License)
  • All of this in about 1,500 lines of code

There are two way you can download this Micro ORM. From Nuget package and GithHub
There are lots of examples available on following page.
http://www.toptensoftware.com/petapoco/ For this example I am going to use SQL Compact edition database. Following a table called “Employee” with 3 fields EmployeeId,FirstName,Lastname.

Same way I have created following Model class similar to above table.

[PetaPoco.TableName("Person")]
public class Employee
{
    public int EmployeeId { get; set; }
    public string  FirstName { get; set; }
    public string LastName { get; set; }
}

I have installed Petapoco via following command in package manager console.

It will install like following.

This will create a PetaPoco.cs file in Model folder. Now we are ready to code so first thing to do is to put a connection string for database in the web.config.
Now its time to write code for the all the operations in controller. Following is a code for index(Listting) in Employee controller. Here you can see I have used the dataContext.Query method of PetaPOCO to fetch data and convert that into Employee class.

public ActionResult Index()
{
    var dataContext = new PetaPoco.Database("sqlserverce");
    var employees = dataContext.Query("Select * from Employee");
    return View(employees);
}

So now Index Action Result method is ready so it’s time to create a strongly type view like below.

So once you click that it will create a strongly type view for listing employees and when you run the code it will look like following.

Following is the code for adding a employee in employee controller. I have created two Action Result Method one for empty form when we create new and another with the httppost attribute to insert employee in database and once insertion is complete it will redirect to list page. If you see the second method I have used db.Insert method to insert data in PetaPOCO. Where we need to pass the table name primary key name and object of employee and it will insert the data.

public ActionResult Create()
{
    return View();  
}

[HttpPost]
public ActionResult Create(Employee employee)
{
    var dataContext = new PetaPoco.Database("sqlserverce");
    dataContext.Insert("Employee", "EmployeeId", employee);
    return RedirectToAction("Index");
}

Now lets create a View for that view via right click view and add view.

Click on add will create a strongly typed view for Employee and when you click on create new.

Same way like the Add I have created two Action Result for editing/updating records one will existing record and another will update the existing record with petapoco and redirect page to the listing page.

public ActionResult Edit(int id)
{
    var dataContext = new PetaPoco.Database("sqlserverce");
    var employee = dataContext.Single("Select * from Employee where employeeId=@0",
                                                     id);
    return View(employee);
}

[HttpPost]
public ActionResult Edit(Employee employee)
{
    var dataContext = new PetaPoco.Database("sqlserverce");
    dataContext.Update("Employee", "EmployeeId", employee);
    return RedirectToAction("Index");
}

In the first Action Result method I have fetch the single records for that employee Id via Single Method of Petapco. While the second method will update the database with update method of PetaPOCO. Now it’s time to create Edit view. I have created edit view like following.

Now when you click edit page from the listing page it will look like following.

Creating detailing page is very similar to Edit Page loading except that it will not save or update anything. Following is a code for that.

public ActionResult Details(int id)
{
    var dataContext = new PetaPoco.Database("sqlserverce");
    var employee = dataContext.Single("Select * from Employee where employeeId=@0",
                                                     id);
    return View(employee);
}

Now code is ready so I have created strongly typed view for detail like following.

Now when you run the page in the browser it will look like following.

You can very easily delete the employee with PetaPOCO with delete method of PetaPOCO where we need to pass type and Id of record just like following. First will load data and ask for confirmation and another will delete the employee record with delete method where we are passing Id and type to delete from the table.

public ActionResult Delete(int id)
{
    var dataContext = new PetaPoco.Database("sqlserverce");
    var employee = dataContext.Single("Select * from Employee where employeeId=@0",
                                                     id);
    return View(employee);
}

[HttpPost]
public ActionResult Delete(int id,FormCollection formCollection)
{
    var dataContext = new PetaPoco.Database("sqlserverce");
    dataContext.Delete(id);
    return RedirectToAction("Index");
}

Now its to time to create a strongly typed view for delete like following.

Now when you run on application the browser it will look like following.

Once you click delete it will return back to index/listing page. That’s it. Hope you like it. Stay tuned more..