MVC Attributes with SubSonic ActiveRecord T4 Templates

By in
No comments

One of my favorite features of the ASP.NET MVC Framework is the ability to include form validation out of the box using Attributes. Marking a Model with the Required attribute and including a few script references enables a built-in framework that validates your forms automatically.

However, my ORM tool, SubSonic, by default doesn’t account for this, as it has its own rules for generatic the code for the data models. However, after playing with the T4 templates for a few minutes, I discovered just how easy it is to manipulate the generated code to fit right into the MVC framework.

In the file somewhere around line 358 is the template code for generating the data model classes. Between the private and public declaration of the individual properties, I simply added a check to see if the column is Nullable

If the column is not Nullable, that means it must have a value, and is therefore required. The CheckNullable method used returns a ? character, so I just used that to determine if the property should be included:

<#=col.SysType #><#=CheckNullable(col)#> _<#=col.CleanName #>;
<# if (CheckNullable(col) != "?") { #> [Required] <# } #>
public <#=col.SysType #><#=CheckNullable(col)#> <#=col.CleanName #>

Now when I look at my generated code, the required properties are now marked with the Required attribute. For example in my model I have a field for collecting a User’s Address, which I need to be required:

string _Address;
public string Address
    get { return _Address; }
    set {
            var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Address");
                if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){

This allows me to now use and I can use this to validate this and any other required properties automatically:


This pretty slick discovery is another on the growing list of reasons I truly enjoy developing with MVC and SubSonic. However, I am curious to see if I can do something similar with OpenAccess, which is the ORM I’ll be using for my next project. More on that when I get there!

The following two tabs change content below.


Senior Developer at iD Tech
Josh loves all things Microsoft and Windows, and develops solutions for Web, Desktop and Mobile using the .NET Framework, Azure, UWP and everything else in the Microsoft Stack. His other passion is music, and in his spare time Josh spins and produces electronic music under the name DJ SelArom. His other passion is music, and in his spare time Josh spins and produces electronic music under the name DJ SelArom.