I founded that NHibernate have several builtin Types that are not present in C#
, but are present in some of SGBD.
Now I have following:
public class TimeSlot : EntityBase
{
public virtual NHibernate.Type.TimeType FromTime { get; set; }
public virtual NHibernate.Type.TimeType ToTime { get; set; }
}
public class TimeSlotMap : ClassMap<TimeSlot>
{
public TimeSlotMap()
{
Id(c => c.Id).GeneratedBy.Identity();
Map(c => c.FromTime);
Map(c => c.ToTime);
}
}
In MSSQL this table look like in attached image
Now when I am trying to query this table I am getting following exception:
Unable to cast object of type 'System.DateTime' to type 'NHibernate.Type.TimeType
What I am doing wrong? And how is Fluent NHibernate working with Time Date Type?
I would suggest, to use TimeSpan
for a DB type Time
public class TimeSlot : EntityBase
{
public virtual TimeSpan FromTime { get; set; }
public virtual TimeSpan ToTime { get; set; }
}
And then NHibernate does have a special type to handle this trick:
Map(c => c.FromTime)
.Type<NHibernate.Type.TimeAsTimeSpanType>();
...
That will allow you to work with a .NET native "time like" type -
Represents a time interval.
If we prefer to use DateTime
, which could be used by NHibernate to express time, we have to do it like this:
public class TimeSlot : EntityBase
{
public virtual DateTime FromTime { get; set; }
public virtual DateTime ToTime { get; set; }
}
And now we can use the type from the question - NHibernate.Type.TimeType
Map(c => c.FromTime)
.Type<NHibernate.Type.TimeType>();
...
Which description is:
/// <summary>
/// Maps a <see cref="System.DateTime" /> Property to an DateTime column that only stores the
/// Hours, Minutes, and Seconds of the DateTime as significant.
/// Also you have for <see cref="DbType.Time"/> handling, the NHibernate Type <see cref="TimeAsTimeSpanType"/>,
/// the which maps to a <see cref="TimeSpan"/>.
/// </summary>
/// <remarks>
/// <para>
/// This defaults the Date to "1753-01-01" - that should not matter because
/// using this Type indicates that you don't care about the Date portion of the DateTime.
/// </para>
/// <para>
/// A more appropriate choice to store the duration/time is the <see cref="TimeSpanType"/>.
/// The underlying <see cref="DbType.Time"/> tends to be handled differently by different
/// DataProviders.
/// </para>
/// </remarks>
[Serializable]
public class TimeType : PrimitiveType, IIdentifierType, ILiteralType
Also check:
Date/Time Support in NHibernate
... Time-related DbTypes stores just the time, but no date. In .NET, there is no Time class and so NHibernate uses a DateTime with the date component set to 1753-01-01, the minimum value for a SQL datetime or a System.TimeSpan – depending on the DbType that we choose...
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