Saturday, August 7, 2010

SubSonic Custom Property Mapping Attributes

Some commits ago we opened SubSonic's property mapping attribute implementation to allow developers to extend how properties are mapped to database columns when using SimpleRepository with migrations.
In this post I'll show you how to implement a custom property mapping attribute that declares a property to be mapped to a database column of type "xml" instead of just a plain nvarchar.

Custom property mapping attributes have to inherit (obviously) from Attribute and implement the IPropertyMappingAttribute interface from namespace SubSonic.SqlGeneration.Schema.

IPropertyMappingAttribute defines the methods Accept and Apply where Accept defines if the Apply method should be invoked for this property. For our implementation we only want to accept properties of type "string". In our apply method we get an IColumn instance passed that we can modify. We can access the Table and Provider property through that IColumn instance if we need it. For our simple implementation this is not needed.

So our final implementation looks like this

public class SubSonicXmlStringAttribute : Attribute, IPropertyMappingAttribute
{
  public bool Accept(IColumn column)
  {
    return column.IsString;
  }

  public void Apply(IColumn column)
  {
    column.DataType = DbType.Xml;
  }
}

If you're using SimpleRepository with auto migratons you'll get every property marked with SubSonicXmlStringAttribute mapped to a database column of type xml. That was easy!

0 comments:

Post a Comment