(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.
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.
You can specify UriType
in a ClassMap<>
:
public class ImportedWebImageMap : ClassMap<ImportedWebImage>
{
public ImportedWebImageMap()
{
Id(x => x.Id);
Map(x => x.SourceUri).CustomType<UriType>();
}
}
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>();
}
}
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"; }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With