gpt4 book ai didi

c# - 在 Fluent Nhibernate 中使用时间类型会生成异常 "Unable to cast object of type ' System.DateTime' 以键入 'NHibernate.Type.TimeType"

转载 作者:太空狗 更新时间:2023-10-30 00:40:35 26 4
gpt4 key购买 nike

我发现 NHibernate 有几个内置类型,它们在 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 中,此表类似于附图 enter image description here

现在,当我尝试查询此表时,出现以下异常:

Unable to cast object of type 'System.DateTime' to type 'NHibernate.Type.TimeType

我做错了什么? Fluent NHibernate 如何使用时间日期类型?

最佳答案

我建议,将 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 native “类时间”类型 -

MSDN - TimeSpan Structure

Represents a time interval.

什么是NHibernate.Type.TimeType那么呢?

如果我们更喜欢使用 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

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

关于c# - 在 Fluent Nhibernate 中使用时间类型会生成异常 "Unable to cast object of type ' System.DateTime' 以键入 'NHibernate.Type.TimeType",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26251926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com