Sitecore Code Generator and O/R mapper

You probably have never used a code generator for the same reason I never used a code generator:

  • It was not developed by yourself
  • It’s not generating the code you need
  • You cannot extend it with the stuff you need
  • They create the same code for all of your Sitecore templates
  • It’s difficult to install
  • It was not developed by yourself.

A code generator that creates an O/R relationship between your Sitecore templates and your code can save you a ton of work though:

  • Automatically update your code when new templates are created
  • There is never any mismatch between your code and Sitecore templates
  • Code class names matches Sitecore template names
  • All field names are mapped correctly

That is why I introduce the open-source, freeware, use-as-you-please:

SITECOREORM, The object/relational code generator for Sitecore.

You can download it here for free, including the source code:

SitecoreORM O/R Mapper and Code Generator


The SitecoreORM is a code generator framework that allows you to create code templates based on well-known user controls (.aspx) pages, and generate code from all of your Sitecore templates.

There is no Sitecore package; all you do is to place the code in your solution and call \sitecore modules\Shell\SitecoreORM\Execute.aspx to execute the code generation.

Out of the box, SitecoreORM generates simple classes that maps all fields on a Sitecore template, references to inherited templates, and a static struct of field names to be used by Sitecore’s sc:FieldRenderer.

But the idea behind SitecoreORM is that you define yourself how your classes should look like.

Changing the output is done by simply changing some .aspx pages. For example, the code template is an .aspx page. This is an example of how it looks (simplified, download the code for the complete example):

namespace <%# Namespace %>
  public class <%# ClassName %> : BaseItem
    public <%# ClassName %>(Item innerItem)
      InnerItem = innerItem;

    public Item InnerItem { get; private set; }

    public override FieldCollection Fields
      get { return InnerItem.Fields; }

    #region Inherited Templates
<%# ExecuteCodeProvider("SomeClass, SomeDll", "SomeParameter") %>

Generating fields, inherited templates or other thing you need, is done using code providers, that you plug in. SitecoreORM uses reflection to find the code, and your class only needs to implement an ICodeProvider interface that has 1 method: Get().

Here is an example of an .aspx file that generates a Sitecore field (a CheckBox field):

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="Sitecore.Data.Items" %>
<%@ Import Namespace="SitecoreORM.CodeProviders" %>
<%@ Import Namespace="SitecoreORM.Services" %>
<script runat="server">

  void Page_Load(object sender, System.EventArgs e)

  private TemplateFieldItem Field
    get { return GenerateFieldProperties.Field; }

  private string PropertyName
    get { return NameNormalizerService.GetValidName(Field.Name); }


    /// <summary>
    /// <%# TemplateFieldItemCommentService.GetComment(Field) %>
    /// </summary>
    public Sitecore.Data.Fields.CheckboxField <%# PropertyName %>
      get { return InnerItem.Fields["<%# Field.Name %>"]; }

The SitecoreORM framework is written with the fewest lines of code that will do the job. The code is as simple as possible, making it easier to extend, and for you to understand.

Features of SitecoreORM includes:

  • O/R mapping Sitecore templates to C# code.
  • Every aspect of the code generation can be customized:
    • .aspx page based code generation allows you to choose the class format yourself.
    • Each field type from Sitecore can be mapped by .aspx pages, making it easy to determine how each field type from Sitecore should be mapped.
    • Inherited templates can be mapped as well.
    • Field names can be mapped to be used by sc:FieldRenderer
    • Plug in your own code; SitecoreORM uses reflection to find the code generators.
  • Customizable output using an include file (/app_config/include/sitecoreorm.config)
    • Determine class name suffixes
    • Determine name space prefixes
    • Determine removing of parts of template path from namespace
    • Determine file destination for generated classes
    • Specify which template folders to ignore (for example /system/ and /common/)
    • Specify which template folders to include
    • Specify file destination for each template folder to include, hence supporting component based development
  • Simple code. Less than 20 classes makes up the framework. 5 services and one repository does most of the job.

Check out SitecoreORM here:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in c#, Sitecore, Sitecore 7 and tagged , , , . Bookmark the permalink.

19 Responses to Sitecore Code Generator and O/R mapper

  1. Vishal Gupta says:

    Hi Brian,

    Similar OR Mapper are already there in market place and one item called DataItem Generator was there from ages like since 2009. Can you please explain how it is different from that or other packages.
    Dataitem Generator is designed by me and Classy Sitecore is another one designed by a company called NTTData. There is another project called glass-lu.
    My point is this Just another mapper or you bring some exiting new innovation.

    Vishal Gupta

  2. briancaos says:

    The SitecoreORM is more of a framework than an actual code generator. It comes out-of-the-box with code templates that will cover your basic needs. But most people like to personalize their code, so SitecoreORM allows you to write your own template for classes, fields, inherited classes etc just by modifying .aspx files.
    You don’t need to compile any code, you don’t need to install any Sitecore package, you don’t need to modify SitecoreORM to do your own specialized code generation.
    SitecoreORM has a set of very limited configuration settings. Especially the feature where you choose the destination folder per template folder is useful for everyone that has seperate dll’s for seperate templates (component based development).

    So agreed – there is not much new apart from the simplicity.

    Before creating SitecoreORM I looked in Sitecore Marketplace for code generators, but only found a field mapper written ages ago. Maybe your DataItem Generator could use a more searchable name in order for it to be found.

  3. Let me answer Vishal’s question by saying that SitecoreORM definitely adds something new. The ease and completeness of customizing the generated classes is wonderful. I went looking for a code generator for Glass Mapper classes and couldn’t find one but I was able to get this one to do what I needed in about fifteen minutes. All I had to do was copy the fieldtemplates folder and customize each field template to use the Glass attributes and data types. No code compilation was necessary. Nice one, Brian. Thanks!

  4. Hi Brian,

    Thanks for sharing!
    Looks like a nice solution and easy to use.

    Unfortunately, my main reason for not using a code generator has not been solved by this:
    – There is no code generator that outputs Glass Mapper models

    If I ever find the time or extreme need for it, I will have to make one of my own – which will also eliminate the “it was not written by me” argument :-)


  5. briancaos says:

    You should talk to Jason Nesbitt, who in fact created Glass Mapped classes using SitecoreORM in 15 minutes. See the comment above for more info.

  6. Lasse Rasch says:

    Hi Brian.

    I never use code generators, mainly because of two reasons :

    1. I of cause like to have strongly typed classes for at least some template types, but not always. And when i create them they often come with some extra custom logic as well that needs to be included, so i have to do manual work either way. And i like having a good feeling about what classes i create and where i put them in my project etc. By using this approach i fear that i loose control of the project (maybe untrue, but this is one of the reasons why i never use ex. Resharper as well).

    2. When i create fields, these are often shared amoung templates. Ex. Navigation title, meta data, settings fields etc. And therefore not defined on each template as such. Will your module here take that into account? I saw you wrote it will create subclasses, but that is really not what you normally want (at least my oppinion). Can it be modified so it can create properties directly on the created classes even though the fields are not defined directly on the items? And what happens if you add extra logic to those classes. Is that overwritten when the module updates the code?

    Also does this module support spaces in fieldnames and will create correct code if that is the case.

    Guess many of these questions is anwsered by downloading the module and trying it out. But i’m asking so that others with the same questions can get anwsers right away :-)

    Keep up the good work.

    Best Regards
    Lasse Rasch

  7. briancaos says:

    Hello Lasse,

    The SitecoreORM is really more of a framework than a finished O/R mapper. It comes preconfigured with a complete mapping example, but the idea is that you customize the mapper to fit your specific needs, f.ex. creating classes for the Sitecore Glass Mapper or any other framework that you might use. It is very easy to add code; the project is just a bunch of .aspx pages, and a set of methods that will call your custom code by reflection.

    When you do shared fields, I presume that you create some shared templates, and then use Sitecore inheritance to reuse these fields on many templates. This is the way I do it, and the mapper will create one class per template, and the templates that inherits other templates will then have a property referencing the inherited template.
    If you want i another way, you write your own .aspx page that duplicates the inherited fields (although I would say that THAT is not the right way to do it), it is very easy.
    And yes, field names are stripped and cleaned, class names are also stripped and cleaned.

    The O/R mapper assumes that everyone writes code differently, and is therefore so flexible that anything is possible.

    You should really download the project and give it a try, you don’t need to install any Sitecore content, and the mapper will not modify any of your existing project logic.

  8. Paul Martin says:

    Hi Brian,

    Why did you decide to generate items that reference fields with the field NAME as opposed to using the field ID?

    Is there some advantage there?


  9. briancaos says:

    There is no advantage at all in using the name and not the ID. For me it’s a conceptual issue.

    I am in opposition to prctically anyone in Pentia on this one, but in general I like to hide ID’s because names carry information about what you are referencing. We generally spend lots of time naming things (variables, classes, Sitecore templates and fields) so why not use it. You would never refer to your front page, or any other page in the content section of your website by the ID, so why refer templates and field names by ID’s?

    Perhaps it’s faster to debug when you have the name directly.

    BTW, if you would like to have ID’s returned instead of names, you should make a new ICodeProvider:

    namespace SitecoreORM.CodeProviders
    public class GenerateFieldIDs : ICodeProvider
    public string Get(TemplateItem template, params string[] parameters)
    StringBuilder sb = new StringBuilder();
    foreach (TemplateFieldItem field in template.OwnFields)
    sb.AppendLine(string.Format(@" public static readonly ID {0} = new ID(""{1}"");", NameNormalizerService.GetValidName(field.Name), field.ID));
    return sb.ToString();

    And reference that class from CodeTemplate.ascx:

    #region field IDs
    public struct FieldIDs
    <%# ExecuteCodeProvider("SitecoreORM.CodeProviders.GenerateFieldIDs, SitecoreORM") %>

  10. Paul Martin says:

    Hi Brian,

    Did you put this up on GitHub or someplace?
    If not, can you? :)

    Nice job by the way… I really like the simplicity.


  11. Paul Martin says:

    Also, regarding Names vs. IDs…

    I agree that seeing the name is much more useful than the ID, but since we’re generating code here, I think hiding the ID behind the name (via your “FieldNames” struct) successfully circumvents that issue.

    Using IDs would also circumvent the issue of the lack of field namespaces. My understanding is that if you have a Base template field with the same name as another field on that template (inherited or not), referencing that field using the name is ambiguous… in that, you’re not sure which field you’re getting. Using Names mapped to IDs gets around this issue since the IDs would be different. Of course, I know Sitecore convention is to name your fields appropriately such that this doesn’t happen in order to avoid this issue.

    Another possible benefit is that the code won’t break if someone decides to rename a template field… at least not until the code file gets regenerated. At which point, you can track down the person renaming template fields and give them “a stern talking to”. One could argue thought that its actually beneficial for it to break right away.

    I think that’s all I’ve got.

  12. briancaos says:

    That’s exactly the same argument I hear from the rest of the Pentia developers. I guess I stand pretty alone with my arguments that Sitecore should never had made the ID’s public.
    Thanks for your post.

  13. Paul Martin says:

    Yes, I grabbed the code already and had made a few tweaks here and there (added some config options) getting it working in our solution. I also have a separate set of changes adapting the output for Bo Breiting’s new ItemBinding framework. (

    Yes, please throw it in GitHub! :)

  14. Paul Martin says:

    Hi Brian – Have you had a chance to upload this to GitHub? Thanks! Paul

  15. Pavlo says:

    Thank you for the code generation, but how do you cast an item to a given class?
    Is there something out-of-the-box?

  16. Pavlo says:

    Thank you for the code generation, but how do you cast an item to a given class?
    Is there something out-of-the-box?
    Thank you

  17. briancaos says:

    There are several frameworks that will help you with that, for example Sitecore Glass Mapper or Sitecore Entity Framework.
    But the SitecoreORM will allow you to create any object that you can cast in any way you like.
    This is the most basic way of creating a class that will help you instantiate a Sitecore Item. In this example I have a Sitecore template called “Page” consisting of a Title and a Text, that I wish to map into an item:

    public class PageModel
    public PageItem(Item innerItem)
    InnerItem = innerItem;

    public Item InnerItem { get; private set};

    public struct FieldNames
    public static string Title = "Title";
    public static string Text = "Text";

    public string Title { get { return InnerItem[FieldNames.Title] }
    public string Text { get { return InnerItem[FieldNames.Text] }

    With a Sitecore Item on one hand and this class in the other hand, you can create a strongly typed model of your item. The model can be used in MVC, WebControls or in code:

    PageModel page = new PageModel(Sitecore.Context.Item);

    The FieldNames struct allows you to use the model in sc:FieldRenderer:

    <sc:FieldRenderer item="" Field="" runat="server"/>

    And the fields will allow you to get the values of an item:

    var someVar = page.Title;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.