Working with Time Type in Fluent Nhibernate generates exception “Unable to cast object of type 'System.DateTime' to type 'NHibernate.Type.TimeType”

断了今生、忘了曾经 提交于 2019-12-05 16:29:39

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 -

MSDN - TimeSpan Structure

Represents a time interval.

What is the NHibernate.Type.TimeType then?

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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!