我发现NHibernate有几个内置的 Types ,它们不存在于C#
中,但存在于某些SGBD中。
现在我有以下内容:
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);
}
}
在MSSQL中,此表看起来像附加图像
现在,当我尝试查询此表时,我遇到以下异常:
无法投射类型&System;日期时间&#39;输入&#39; NHibernate.Type.TimeType
我做错了什么? Fluent NHibernate如何使用Time Date Type?
答案 0 :(得分:7)
我建议,将TimeSpan
用于数据库类型Time
public class TimeSlot : EntityBase
{
public virtual TimeSpan FromTime { get; set; }
public virtual TimeSpan ToTime { get; set; }
}
然后NHibernate确实有一种特殊类型来处理这个技巧:
Map(c => c.FromTime)
.Type<NHibernate.Type.TimeAsTimeSpanType>();
...
这将允许您使用.NET本地&#34;时间像&#34;输入 -
表示时间间隔。
如果我们更喜欢使用NHibernate可以用来表达时间的DateTime
,我们必须这样做:
public class TimeSlot : EntityBase
{
public virtual DateTime FromTime { get; set; }
public virtual DateTime ToTime { get; set; }
}
现在我们可以使用问题中的类型 - NHibernate.Type.TimeType
Map(c => c.FromTime)
.Type<NHibernate.Type.TimeType>();
...
描述是:
/// <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
同时检查:
Date/Time Support in NHibernate
...与时间相关的DbTypes只存储时间,但没有日期。在.NET中,没有Time类,所以NHibernate使用DateTime,日期组件设置为1753-01-01,SQL datetime或System.TimeSpan的最小值 - 取决于我们选择的DbType ...