NHibernate Sqldatetime必须在1/1/1753和12/31/9999之间

erk*_*mir 4 c# sql-server nhibernate

我在我的MVC项目中使用NHibernate.我的问题是,当我试图更新一个对象后,我得到跟随错误.

SqlDateTime溢出.必须在1/1/1753 12:00:00 AM和12/31/9999 11:59:59 PM之间.

在调试模式下,我看到date属性不为null.我在映射上设置了Datetime nullable.但我仍然得到sqldatetime错误.

public class EntityBaseMap<T> : ClassMap<T> where T : EntityBase
{
    public EntityBaseMap()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        Map(x => x.IsDeleted).Not.Nullable();
        Map(x => x.CreatedAt).Nullable();
        Map(x => x.UpdatedAt).Nullable();
        Map(x => x.Random).Formula("NEWID()");

        References(x => x.Status).Column("StatusId");

        Where("IsDeleted=0");
    }
}
Run Code Online (Sandbox Code Playgroud)

保存时,日期时间属性不为空.

public int SaveOrUpdatePage(PageDto PageDto)
{
    var page = PageDto.Id > 0 ? ById<Page>(PageDto.Id) : new Page();
    var status = PageDto.Status.Id > 0 ? LookupById<Status>(PageDto.Status.Id) : null;
    var type = PageDto.Type.Id > 0 ? LookupById<PageType>(PageDto.Type.Id) : null;
    //var parent = PageDto.Parent.Id > 0 ? ById<Page>(PageDto.Parent.Id) : page.Parent;

    page.Description = PageDto.Description;
    page.Title = PageDto.Title;
    page.SpotText = PageDto.SpotText;
    page.Status = status;
    page.Text = PageDto.Text;
    page.Url = !string.IsNullOrEmpty(PageDto.Url) ? PageDto.Url.ToFileName() : PageDto.Title.ToFileName();
    page.Featured = PageDto.Featured;
    page.Type = type;

    using (var tran = UnitOfWork.CurrentSession.BeginTransaction())
    {
        UnitOfWork.CurrentSession.SaveOrUpdate(page);
        tran.Commit();
    }


    page.CreateDirectory();

    if (PageDto.Id == 0)
    {
        page.Copy();
        page.CopyThumbs();
    }

    SetResultAsSuccess();

    return page.Id;
}
Run Code Online (Sandbox Code Playgroud)

我使用SQLServer 2008并在表datetime列上检查allow null.

Rad*_*ler 7

这不是一个问题,NULL或者NULLABLE列.这是DateTimeValueType 的C#默认值的问题.

default(DateTime) == new DateTime(1,1,1) // 1st January of year 1 
Run Code Online (Sandbox Code Playgroud)

因此,因为CreatedAt或UpdatedAt被定义为

public virtual DateTime CreatedAt { get; set; }
public virtual DateTime UpdatedAt { get; set; }
Run Code Online (Sandbox Code Playgroud)

并且永远不会设置为默认值以外的值...哪个值为1.1.0001.这比SQL Server下限1.1.1753少......

换句话说,请确保将这些值设置为某些有意义的值,例如 DateTime.Now

  • 可能......但是肯定问题是不同的专栏.简单 - 几乎总是 - 我的意思是**99,98%**案例,这个问题意味着:有一个`DateTime`属性不是`DateTime?`.此类属性未使用自定义值设置,只保留默认值1.1.0001.检查carefuly异常(你会看到哪个列是错误的)然后肯定你会看到它的值(在调试中)留在`default(DateTime)`...希望它有点h (3认同)