9

I have a table with a time column in my SQL Server 2008 database.

The property of the object I'm trying to map to is a TimeSpan.

How can i tell FluentNHibernate to use the TimeAsTimeSpan NHibernate type, so that I don't have cast problems?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Guillaume Davion
  • 434
  • 4
  • 12

3 Answers3

7

This is working for me:

Map(x => x.TimeFrom)
    .CustomType("TimeAsTimeSpan");
Ian Nelson
  • 57,123
  • 20
  • 76
  • 103
  • That works, but how do you deal with NULL values in the database? TimeSpan.Zero is equal to new TimeSpan(0,0,0) so that won't work, and gets persisted as "00:00:00" by NHibernate's TimeAsTimeSpanType. Poking through the source-code, it does not appear to handle NULL-values at all? Whether I put NULL or "00:00:00" in a column, this comes back from NHibernate as TimeSpan.Zero either way. What gives? – mindplay.dk May 27 '11 at 17:57
  • 3
    @mindplay.dk `TimeSpan` can't represent `null`. `TimeSpan?` can. – ta.speot.is Oct 08 '13 at 03:40
5

And if you're using the conventions, then this does the job for me:

public class PropertyConvention : IPropertyConvention 
{
    public void Apply(IPropertyInstance instance)
    {
        if (instance.Property.PropertyType == typeof(TimeSpan))
            instance.CustomType( "TimeAsTimeSpan" );
    }
}
David Gardiner
  • 16,892
  • 20
  • 80
  • 117
0

You should be able to map it using CustomType.

Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
  • What do I put in CustomType? TimeAsTimeSpan or DBType.Time? With TimeAsTimeSpan I get an exception as the type doesn't have a constructor with no parameters – Guillaume Davion Feb 19 '10 at 16:07
  • The first line of the linked article is "CustomType("TimeAsTimeSpan") should work fine". – Jamie Ide Mar 25 '10 at 12:17