c# - 使用 Fluent NHibernate 和 MVC 3 的 SqlDateTime 溢出

标签 c# asp.net-mvc-3 fluent-nhibernate sql-server-express

我正在使用 FNH 生成 ASP.NET MVC3 应用程序中使用的库的大约 30 个类的映射。我正在使用 MSSQL Express 10。我创建了一些代码,允许我使用一些数据填充数据库以用于开发目的。但是,当我尝试保存帐户实例时,收到以下错误消息:

System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

发生这种情况是因为 Account.CreationDate 属性,它是一个 DateTime。我环顾四周,发现 MSSQL 和 .NET 中的 DateTime 实际上并不相同。我尝试过,通过 FNH 映射强制该列为“datetime2”,但这似乎没有帮助。

这是我的帐户类(简化):

public class Account
{
    public virtual int Id { get; set; }
    public virtual string Comment { get; set;}
    public virtual DateTime CreationDate { get; set;}
    public virtual string Email { get; set;}
    public virtual string Password {get ; set;}
    public virtual string Locale {get; set;}

    public Account(string password, string email)
    {
        this.Email = email;
        SetNewPassord(password);
        this.CreationDate = DateTime.Now;
        this.Locale = "en-US";
    }
}

以及 FNH 映射:

public class AccountMap : ClassMap<Account>
{
    public AccountMap()
    {
        Id(x => x.Id);
        Map(x => x.Comment);
        Map(x => x.CreationDate);
        Map(x => x.Email);
        Map(x => x.Password);
        Map(x => x.Locale);
    }
}

我称之为的代码:

        var compteAdmin = new Account("test", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ae4e5e5e4efcae4e5fde2eff8efa4e9e5e7" rel="noreferrer noopener nofollow">[email protected]</a>");
        compteAdmin.Locale = "fr-FR";
        var toto = compteAdmin.CreationDate;
        try
        {
            session.Save(compteAdmin);
        }
        catch (Exception ex)
        {
            throw new ConfigurationException("Account.CreationDate: " + compteAdmin.CreationDate.ToString() + " ; Exception: " + ex);
        }

请注意,为了调试的目的,我抛出了一些异常。其输出有点超现实!

Account.Creation date: 2/6/2013 5:32:29 PM ; Exception: System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

最佳答案

问题是 DateTime 属性未设置为“可空”,因此该属性没有设置为“空”,而是不断设置为 01/01/0001,因此触发了超出范围的错误。

因此,在类(即:public virtual DateTime? CreationDate { get; set;})以及映射(Map(x => x .CreationDate).Nullable;) 是必需的。

如果不这样做,即使您将该属性设置为 null,它也会显示为 01/01/0001。一旦属性设置为可为空,它的值就真的为空,并且查询成功。

关于c# - 使用 Fluent NHibernate 和 MVC 3 的 SqlDateTime 溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14734425/

相关文章:

c# - 具有自引用功能的 Fluent NHibernate 自动映射

c# - 流畅的 NHibernate 映射 : one-to-one (or none)

c# - 双指缩放大图像?

entity-framework-4 - 使用 POCO 和 ViewModel 的 MVC3 EF 模型优先

asp.net-mvc-3 - MVC 3到./bin/的相对路径

c# - 在 ASP.NET MVC 3 中注入(inject) IPrincipal - 我做错了什么?

c# - VS MSTest runner 在内存测试中运行时锁定 System.Data.SQLite.dll

c# - WPF 中的文本框绑定(bind)更新

c# - 有没有办法从 C# 调用/运行 JavaScript?

c# - 通过任何版本的 Outlook 发送电子邮件