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 ActiveRecord.tt 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;
[Required]         
public string Address
{
    get { return _Address; }
    set {
        if(_Address!=value){
            _Address=value;
            var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Address");
            if(col!=null){
                if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                    _dirtyColumns.Add(col);
                }
            }
            OnChanged();
        }
    }
}

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

item-validation

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.

selaromdotnet

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.