我正在组建一个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);