Sunday, 18 January 2009

Automatically serializing value objects using Fluent NHibernate

After reading James Gregory's posts on Fluent NHibernate (in particular http://blog.jagregory.com/2009/01/11/fluent-nhibernate-auto-mapping-type-conventions/) I had a quick play and came up with this.

It's very cool how FNH will generate your database for you, but sometimes you want to have a value object instead of an entity, so I have created a generic class you can use which will serialize an object into a field automatically, so add something like this to your FNH conventions.

.WithConvention(c => c.AddTypeConvention(new AutoTypeConvention<LatLng>()))

So now my class

public class Venue
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual LatLng Location { get; set; }
}

Will have the following SQL generated for it by FNH/SchemaExport

create table [Venue] (
  Id INT IDENTITY NOT NULL,
   Location NVARCHAR(MAX) null,
   Name NVARCHAR(100) null,
   primary key (Id)
)

The LatLng object will be serialized into the NVARCHAR(MAX) column automatically. Neato! Warning - you should only do this with immutable types (I think) and you might want to use a version tolerant serialization strategy in case the definition of your value type changes from the version serialized in the db. I've provided an XML serializer implementation, feel free to change it!

You can get the code from here (apologies for the file hosting)

UPDATE: The xml serializer is a bit broken - get the latest from http://refactormycode.com/codes/710-polymorphic-xml-serializer#refactor_144121

Submit this story to DotNetKicks