user981375
user981375

Reputation: 647

NHibernate and SQL 2008 Time datatype

How do I map NHibernate type to SQL Server's TIME type? I'm using NH 3.2 and map-by-code.

public class Schedule
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual TimeSpan Time { get; set; }
}

Here is my mapping class

public class ScheduleMapping : ClassMapping<Schedule>
{
    public ScheduleMapping()
    {
        Id(x => x.Id, x => x.Generator(Generators.Native));
        Property(x => x.Name, x => x.NotNullable(true));
        Property(x => x.Time, x => x.NotNullable(true));
    }
}

Now, when I create database from this column "Time" has BIGINT SQL type instead of TIME. I have read this and that article but it's not clear to me how to apply any of these solutions.

=========== EDIT ====================

I created and inserted new schedule like this:

var newSchedule = new Schedule {
                   Name = "My Schedule",
                   Time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0)
                   };
session.SaveOrUpdate(newSchedule);

When this data was inserted (around 7:27 PM) the Time column contained value '700200000000', which could be ticks, but the most important thing was that when I queried DB for these values

var retrievedSchedules = session.QueryOver<Schedule>().List();

the Time property was properly set to 19:27.Originally I wanted Time property to represent the time at which Schedule is supposed to run. Even though SQL Server's datatype for this column was defined as BIGINT and the value is represented as (most likely) ticks, after retrieval it was correctly transited into a time, which is what I wanted. This no longer is a question but I'm going to leave this for, hopefully, someone else's benefit.

Upvotes: 7

Views: 2472

Answers (1)

Thilak Nathen
Thilak Nathen

Reputation: 1333

This, in your mapping should solve your problem:

Property(x => x.Time, x => x => { x.NotNullable(true); x.Type<TimeAsTimeSpanType>(); });

By default, NH will use x.Type<TimeSpanType>() as the NH type for the clr Time type ... which maps to the SQL Server 2008 as a bigint.

Have a look here: http://jameskovacs.com/2011/01/26/datetime-support-in-nhibernate/. It covers the different Clr --> NH --> Db type mappings for dates & times.

Upvotes: 3

Related Questions