Chris
Chris

Reputation: 27599

Automapping custom types

I am in the process of setting up nhibernate using fluent nhibernate for a relatively simple setup. Automapping is able to do everything currently fine except for one property on my objects.

I have properties of type MongoDB.Bson.ObjectId. This is simple immutable struct that basically represents a binary ID that can be easily represented in string format as well. These properties cause NHibernate to throw an error saying:

An association from the table PostView refers to an unmapped class: MongoDB.Bson.ObjectId

This is quite expected of course because I don't expect nhibernate to understand what ObjectId is.

Where I am stuck is that what I want is to be able to tell Nhibernate to map this object type to a string representation in the database. I would like to be able to do this while still using automapping so I don't have to explicitly map all of those objects - what I'd like is to be able to just say "Whenever you find this objecttype use this mapping". I've found mention of NHibernate.UserTypes.IUserType which seems to look like it does what I want but I've found nothing that usefully tells me how to use it.

So to summarise the question:

How can I automatically map a custom data type to a known type for storing in the database (and of course the reverse).

I would prefer not to change my objects to storing the string representation of the object if possible.

Upvotes: 0

Views: 353

Answers (1)

Athina
Athina

Reputation: 533

You have to write a convention for this type. Something like this:

public class CustomTypeConvention : IUserTypeConvention
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Property.PropertyType == typeof(MyType));
    }

    public void Apply(IPropertyInstance target)
    {
        target.CustomType(typeof(string));
    }
}

And add this convention to mappings:

mapping.Conventions.Add(new CustomTypeConvention());

Upvotes: 1

Related Questions