c#将datetime2数据类型转换为日期时间数据类型导致超出范围的值

时间:2015-04-18 14:25:03

标签: c# asp.net sql-server asp.net-mvc datetime

我正在组建一个C#Asp.net MVC网站。其中一个模型是SystemUser,如此处所示

public class SystemUser : DefaultModel
{
    public int Id { get; set; }

    [Required]
    [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
    [Column("FirstName")]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Display(Name = "Full Name")]
    public string Name
    {
        get
        {
            return string.Format("{0},{1}", this.FirstName, this.LastName);
        }
    }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    [Display(Name = "Hire Date")]
    public DateTime HireDate { get; set; }

    [Required]
    public int inactive { get; set; }

    public virtual ApplicationUser User { get; set;  }

    public string ApplicationUserId { get; set; }

}

SQL Server数据库表def看起来像这样

CREATE TABLE [dbo].[SystemUser] (
[Id]                INT            IDENTITY (1, 1) NOT NULL,
[LastName]          NVARCHAR (50)  NOT NULL,
[FirstName]         NVARCHAR (50)  NOT NULL,
[HireDate]          DATETIME       NULL,
[inactive]          INT            NOT NULL,
[ApplicationUserId] NVARCHAR (128) NULL,
[CreatedDate]       DATETIME       DEFAULT (getdate()) NOT NULL,
[UpdatedDate]       DATETIME       DEFAULT (getdate()) NOT NULL,
[UpdatedUserId]     INT            DEFAULT ((0)) NOT NULL,
CONSTRAINT [PK_dbo.SystemUser] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.Person_dbo.AspNetUsers_ApplicationUserId] FOREIGN KEY ([ApplicationUserId]) REFERENCES [dbo].[AspNetUsers] ([Id])
);
GO
CREATE NONCLUSTERED INDEX [IX_ApplicationUserId]
ON [dbo].[SystemUser]([ApplicationUserId] ASC);

在网站上使用注册页面时,凭据将以默认AccountController进行处理。我已经修改了这个,通过在Register方法中添加四行代码来创建SystemUser,如下所示。

if (result.Succeeded)
{
    var db = new ApplicationDbContext();
    var systemUser = new SystemUser { FirstName = model.FirstName, LastName = model.LastName, inactive = 0, ApplicationUserId = user.Id, HireDate = DateTime.Now };
    db.SystemUsers.Add(systemUser);
    db.SaveChanges();

当我运行注册处理时,记录被插入到AspNetUsers表中确定,然后我在db.SaveChages();调用上收到例外,如下所示,

  

datetime2数据类型转换为datetime数据类型   导致超出范围的价值。声明已经终止。

Line 160: var systemUser = new SystemUser { FirstName =  model.FirstName, LastName = model.LastName, inactive = 0, ApplicationUserId = user.Id, HireDate = DateTime.Now };
Line 161: db.SystemUsers.Add(systemUser);
Line 162: db.SaveChanges();
Line 163:
Line 164: await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

2 个答案:

答案 0 :(得分:1)

DATETIME仅限于1753年1月1日00:00:00,截至9999年12月31日23:59:59.997,所以请确保您没有传递任何其他值。

您可以将DATETIME字段的类型更改为DATETIME2,也可以添加其他验证。

答案 1 :(得分:0)

你可以改变你的表,使用datetime2代替HireDate列的datetime类型。