Mapping a URI for a String in Fluent NHibernate

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

I would like to map a class that has a URI member in a string column using NHibernate. How exactly can I do this?

I do not think that the solution asked for the corresponding question works here - I cannot declare a private field and match it, because the mapping must refer to this field.

+4
source share
2 answers

If you don't need to do something, the UriType provided by NHibernate will work (I don't know which version has been introduced - I use 3.1.4000). No need to write a custom user type.

Classmap

You can specify UriType in ClassMap<> :

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

Property Convention

You can use the hardware agreement 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>(); } } 

Saving as varchar

If you want to save the Uri in the database as varchar and not the default nvarchar , you can create a non-standard type, which is obtained from UriType and indicates the SQL type AnsiString :

 public class UriAnsiStringType : UriType { public UriAnsiStringType() : base(new AnsiStringSqlType()) { } public override string Name { get { return "UriAnsiStringType"; } } } 
+8
source

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

Fluent NHibernate doesn't do this as easily as standard HBM files, but there are several ways to do this. See the Fluent NHibernate Wiki for instructions.

Alternatively, I think you will need to define an IUserType class that can load / save the value as a string. An example of this with Fluent NHibernate can be found at the end of this blog post .

+3
source

All Articles