Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a URI to string in Fluent NHibernate

(See this related question for LINQ-to-SQL)

I'd like to map a class that has a URI member to a string column using NHibernate. How exactly might I accomplish that?

I don't think the solution given to the related question works here - I can't declare a private field and map it, because the mapping needs to reference that field.

like image 729
ripper234 Avatar asked Dec 19 '09 18:12

ripper234


1 Answers

Unless you need to do something special, UriType provided by NHibernate will work (I don't know what version it was introduced - I am using 3.1.4000). No need to write a custom user type.

ClassMap

You can specify UriType in a ClassMap<>:

public class ImportedWebImageMap : ClassMap<ImportedWebImage>
{
    public ImportedWebImageMap()
    {
        Id(x => x.Id);
        Map(x => x.SourceUri).CustomType<UriType>();
    }
}

Property Convention

You can use a property convention to map all Uri properties to use UriType:

public class UriConvention : IPropertyConvention
{
    public void Apply(IPropertyInstance instance)
    {
        if (typeof(Uri).IsAssignableFrom(instance.Property.PropertyType))
            instance.CustomType<UriType>();
    }
}

Storing as varchar

If you want to store the Uri in the database as varchar rather than the default nvarchar you can create a custom type that derives from UriType and specifies the AnsiString SQL type:

public class UriAnsiStringType : UriType
{
    public UriAnsiStringType()
        : base(new AnsiStringSqlType())
    { }

    public override string Name
    {
        get { return "UriAnsiStringType"; }
    }
} 
like image 158
mattk Avatar answered Oct 09 '22 21:10

mattk