0

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.

Chris
  • 27,210
  • 6
  • 71
  • 92

1 Answers1

1

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());
Athina
  • 533
  • 5
  • 20
  • How will that decide how to serialise MyType to string? I've been playing with a solution involving a custom type map implementing IUserType but are you saying that I can get by with the above without telling it about my IUserType? – Chris Jun 03 '14 at 13:01
  • Sorry, you can't use it just like this if you have MyType. But maybe with MongoDB.Bson.ObjectId you cann just like you can with Guid. If you have more complex type you have to use IUserType. The best explanation I found is here http://blog.miraclespain.com/archive/2008/Mar-18.html with the UriType. Copy this UriType and change what you have to for MongoDB.Bson.ObjectId type. – Athina Jun 03 '14 at 14:13