我正在使用 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/