The new data layer in Umbraco 6

By Markus Johansson
2013-01-24

I actually started working on this blog post when i was i Thailand over Christmas. I sat down at the beach cafe by our hotel and my view looked something like this:

IMG_2878

 

Perfect condition for reading the new Umbraco 6 source code! =D

New data layer using PetaPoco

The new data layer in Umbraco 6 is using the superfast Mirco ORM PetaPoco which is aaaaalmost as fast as hand coding the SQL queries with the ADO.NET classes – any case it’s a lot faster then ie. EF or nHibernate.

 

I used PetePoco in one of my projects about a year ago and I’m very happy with how it works. The implementation in Umbraco is even better than the “standard” PetaPoco as it comes with some extra classes and helper that helps you make the SQL-queries even more database agnostic.

Demo 1.0

Just to show you how simple it is to use the new data layer to fetch data from custom tables I’ll show you the simplest example.

 

I this example we have a custom table in the Umbraco database called 'ext_Contacts' which has three columns: ContactId, Name and Phone. First we create a POCO class to act as our model.

 

public class Contact
{
  public Int32 ContactId { get; set; }
  public String Name{ get; set; }
  public String Phone{ get; set; }
}


This object has no idea of what context it’s used in, it doesn't know anything about Umbraco, PetaPOCO or any other infrastructure in the project. To use the Umbraco data layer to receive a collection of contacts from the database you just simply use the this code:

 

// Get the current database object
var db = ApplicationContext.Current.DatabaseContext.Database;
// Fetch a collection of contacts from the db.
var listOfContacs = db.Fetch<Contact>(new Sql().Select("*").From("ext_Contacts"));

 

 This code looks like any other PetaPOCO implementation and you could download a stand alone version of PetaPOCO and use this in you own (non Umbraco) project in the same way. The Fetch-method is smart enough to grab the data from the db-table and map it to the Contact-object. If your properties don’t match the column name you will need to do some configuration to get this working.

 

The great thing with this code is that it will work no matter which database you are running on – you don’t have to care. I’m going to use this approach in the next version of Newsletter Studio for Umbraco to rewrite the data access layer to not use EF any more.

 

With all this said you should not use this method to fetch content, media, members or anything else from the Umbraco core – then you should use the new Services that Niels Hartvig explains in this blog post.






More blog posts



15 januari 2021

Umbraco and MiniProfiler