c# - 使用 C# 和 Fluent Nhibernate 在 MySQL 中使用 DateTime 保存毫秒精度

标签 c# mysql fluent-nhibernate

我一直在尝试将 C# DateTime 保存到 MySQL datetime(6),但没有取得太大成功。我需要以毫秒精度存储日期时间。 这是我设置测试表的方法。

create table test_date_time
( 
    ID int not null auto_increment
    , Created_By datetime(6)
    , primary key (ID) 
);

在 C# 中,我指定实体类型和字段映射,如下所示:

public class test_date_time
{
    public virtual long ID { get; set; }

    public virtual DateTime? Created_By { get; set; }
}

public class test_date_time_Map : ClassMap<test_date_time>
{
    public test_date_time_Map()
    {
        Id(x => x.ID);
        Map(x => x.Created_By);
    }

}        

这是我如何连接到数据库并存储日期时间:

string Connection_String = string.Format(@"Server={0};Database={1};Uid={2};Pwd={3};SSL Mode=Required;CertificateFile={4};"
    , Server, Database, User, Password, Certificate_File);

ISessionFactory Session_Factory = Fluently.Configure()
    .Database(MySQLConfiguration.Standard.ConnectionString(Connection_String))
    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<test_date_time_Map>())
    .BuildSessionFactory();

var Session = Session_Factory.OpenSession();

var t = new test_date_time() { Created_By = DateTime.UtcNow };
Session.SaveOrUpdate(t);

Session.CreateCriteria<test_date_time>().List<test_date_time>();

var Status = Session.CreateCriteria<test_date_time>().List<test_date_time>();

Session.Close();

通过阅读各种帖子,我还尝试通过以下方式将映射更改为自定义类型:

public class test_date_time_Map : ClassMap<test_date_time>
{
    public test_date_time_Map()
    {
        Id(x => x.ID);
        Map(x => x.Created_By).CustomType("datetime(6)");
    }

}  

但这只会导致异常“无法确定类型:datetime(6),对于列:NHibernate.Mapping.Column(Created_By)”

有人知道如何保存亚秒精度吗?

最佳答案

使用 NullSafeSet 实现创建一个新的用户类型(实现 IUserType),以所需的精度执行 ToString()。 (例如,DateTimeWithMilliseconds)

然后,您可以编写自定义约定以将其应用于所有日期时间(如果您使用自动映射),或者执行以下操作:

Map(x => x.Created_By).CustomType<DateTimeWithMilliseconds>()

在您的映射中。

关于c# - 使用 C# 和 Fluent Nhibernate 在 MySQL 中使用 DateTime 保存毫秒精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34110503/

相关文章:

php - 更新不同的数据库和表

mysql - 在社交网站中使用逗号存储好友关系

mysql - NHibernate 数据库创建后如何将固定数据插入数据库?

nhibernate - Fluent NHibernate - SessionSource 和 PersistenceSpecification

nhibernate - PrimaryKeyNamingConvention Fluent Automapping

c# - SingleProducerConstrained 和 MaxDegreeOfParallelism

c# - 如何捕获 OutlookContact.Write 事件?

c# - 验证元素的未转义长度

c# - 资源 (resx) 文件导入

php - 动态为mysql查询中的所有字段名分配别名