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.
As per topten software it contains following features.
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.
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.
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.
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.
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.
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.
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..
What is PetaPoco?
- 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
Features of PetaPoco:
- 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
How to download:
Examples:
http://www.toptensoftware.com/petapoco/
Creating table for CRUD operation:
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; } }
Installing NuGet Package for petapoco:
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.
<add name="sqlserverce" connectionString="Data Source=C:\Users\Lenovo\Documents\Visual Studio 11\Projects\MvcApplication1\MvcApplication1\App_Data\Employee.sdf" providerName="System.Data.SqlServerCe.4.0" />
Listing/Displaying Employee in ASP.NET MVC and PetaPOCO:
public ActionResult Index() { var dataContext = new PetaPoco.Database("sqlserverce"); var employees = dataContext.Query<Employee>("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.
Creating employee in ASP.NET MVC and PetaPOCO:
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.
Updating employee records with ASP.NET MVC and PetaPOCO:
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<Employee>("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 Employee detail page with ASP.NET MVC And PetaPOCO:
public ActionResult Details(int id) { var dataContext = new PetaPoco.Database("sqlserverce"); var employee = dataContext.Single<Employee>("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.
Creating Delete Page with ASP.NET MVC and PetaPOCO:
public ActionResult Delete(int id) { var dataContext = new PetaPoco.Database("sqlserverce"); var employee = dataContext.Single<Employee>("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<Employee>(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..
Hi Jalpesh,
ReplyDeleteCan we use store procedure in petapoco if yes then provide way how to use
Hello Kirti,
ReplyDeleteYes its possible. I have already posted a blog entry for this.
http://www.dotnetjalps.com/2011/06/petapoco-with-parameterised-stored.html
Regards,
Jalpesh
Thanks Jalpesh.
ReplyDeleteNice article its very usefull,
ReplyDeleteWe can also submit our dotnet related article links on http://www.dotnettechy.com to increase trafic. it is kind of social networking for dotnet professionals only
You're welcome
ReplyDeletethanks I will look into it.
ReplyDeleteNo Linq = Turn Off. It might be good for spikes, but for an enterprise level application it will fall on it's head.. !!
ReplyDeleteI don't understand what you are saying can you please tell me in brief.
ReplyDeleteHi, There is one issue that i am facing is that, With Sql sub qeury there is count(*) records and in maing query i am refrencing with Petapoco.Resultcolumn, but counter always showing 0, please help me if any idea..There is not much documentaion for Petapoco Result column with sub query count(*) records, on their official site Count(*) to result column example is with main query not with sub query...
ReplyDeleteRegards
Hi Kalpesh,
ReplyDeleteCan you please send me a code.
This is a very nice article on "CRUD Operations Using Entity Framework in ASP.NET MVC". I have find out some other articles link from which I have learnt "CURD operations using Ajax Model Dialog in ASP.NET MVC!". I think this is very helpful for developers like me.
ReplyDeletehttp://www.mindstick.com/Articles/279bc324-5be3-4156-a9e9-dd91c971d462/?CRUD%20operation%20using%20Modal%20d
http://www.dotnet-tricks.com/Tutorial/mvc/42R0171112-CRUD-Operations-using-jQuery-dialog-and-Entity-Framework---MVC-Razor.html
How to insert an image and retrieve,update from database in mvc,
ReplyDeletePlease give me complete example on this
Sure I will post in future post
ReplyDeleteplease post as soon as possible,
ReplyDeleteSend me simple&complete code example for this
send me my mailid: mandla.anilbabu@gmail.com
Sure I will try my best
ReplyDeletethank you
ReplyDeletevery nice explanation of petapoco with MVC....thank you..1
ReplyDeletethank you for help us
ReplyDelete