Fixed working with time type in Fluent Nhibernate "Cannot apply object of type" System.DateTime "to type" NHibernate.Type.TimeType "
I founded NHibernate for several built-in types that are not present in C#
, but are present in some of the SGBDs.
Now I have the 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 is similar to the attached image
Now when I try to query this table, I get the following exception:
Cannot overlay object of type 'System.DateTime' on type 'NHibernate.Type.TimeType
What am I doing wrong? And how does Fluent NHibernate work with the date type?
source to share
I would suggest using TimeSpan
for DB typeTime
public class TimeSlot : EntityBase
{
public virtual TimeSpan FromTime { get; set; }
public virtual TimeSpan ToTime { get; set; }
}
And then NHibernate has a special type to handle this trick:
Map(c => c.FromTime)
.Type<NHibernate.Type.TimeAsTimeSpanType>();
...
This will allow you to work with the .NET native "type time" -
MSDN - TimeSpan Structure
Represents a time interval.
What is NHibernate.Type.TimeType then?
If we prefer to use DateTime
which NHibernate can use to express time, we should 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 question type - NHibernate.Type.TimeType
Map(c => c.FromTime)
.Type<NHibernate.Type.TimeType>();
...
What's the description:
/// <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 and time support in NHibernate
... Time-bound DbTypes only store the time, not the date. There is no Time class in .NET, so NHibernate uses DateTime with date component set to 1753-01-01, minimum value for SQL time, or System.TimeSpan - depending on the selected DbType ...
source to share