5

(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.

Community
  • 1
  • 1
ripper234
  • 222,824
  • 274
  • 634
  • 905

2 Answers2

9

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"; }
    }
} 
mattk
  • 1,335
  • 1
  • 14
  • 19
3

The same solution would work fine; You could define the string property as private so it is not exposed to anyone.

Fluent NHibernate doesn't handle this as easily as standard HBM files, but it can be done a few ways. See the Fluent NHibernate Wiki for instructions.

Alternatively, I think you'd have to define an IUserType class that can load/save the value as a string. Example of doing this with Fluent NHibernate can be found at the end of this blog post.

Chris Shaffer
  • 32,199
  • 5
  • 49
  • 61