Exploring the usage of T4 templates in Umbraco

Published on Friday, September 11, 2015

When exploring Pluralsight to find new interesting things that could be useful I stumbled upon T4 templates which I've thought about trying out for a while. Finding use-cases for just "trying things out" can be a bit challenging but I decided to check out if it were possible to do something new with our revised LinqToUmbraco package.

The source template is located in the attached file section!

Note that the implementation described below are just as a proof of concept.


Would it be possible to automatically build new classes containing field information from Umbraco document types? What more can we do?

The implementation

Retrieving document type information

I started out experimenting a bit with retrieving and defining the document types (content types) directly from the database of my Umbraco installation (mind you that this a prototype and the direct database connection should be replaced with something more long-lasting and dynamic).

SELECT * FROM [cmsContentType] 
 left join (SELECT parentContentTypeId as parentId, childContentTypeId as childNodeId FROM [cmsContentType2ContentType]) as Mapping ON Mapping.childNodeId = nodeId

The above SQL statement retrieves all different content types and their parent (which content type they inherit from).

They are then stored in a list and their properties are retrieved from the database.

SELECT [Description], [helpText], [Alias], [Name], [dbType], DataType.nodeId as DataTypeId
FROM [cmsPropertyType]
left join 
(SELECT [pk]
FROM [cmsDataType]) as DataType on DataType.nodeId = dataTypeId where contentTypeId = " + typeId

Above the variable typeId is the id of the content type.

The next thing that happens are that the property value types are guessed by checking the property data type and their stored type in the database (Ntext, Nvarchar etc.). These guesses are used in the template generation to decide which type the returned objects should have.


The configuration in this experimental implementation consists of the database connection settings and the generated code namespace.

var Server = "";
var Username = "";
var Password = "";
var UseIntegratedSecurity = false;
var Database = "";
var GeneratedNamespace = "LinqToUmbraco";
Using the generated code
// Retrieve a typed node
Master master = Umbraco.Single();
string backgroundImage = master.BackgroundImage;
// Already on a master page and want to use pre-defined field names instead of strings? No problem!
var backgroundImage = Model.Content[Master.FieldNames.BackgroundImage];
// Want to convert an already retrieved IPublishedContent node? No sweat
Master master = Umbraco.TypedContent(myPublishedContentNode);
// or convert it as following
Master master = myPublishedContentNode.To();
// Check type without strings
    // Our content is the document type Master


Download Umbraco T4 Templates

comments powered by Disqus