如何将 Null 值传递给 ASP.Net Identity User Table 中的 datetime?

How to pass Null value to datetime in ASP.Net Identity User Table?

我已经在身份用户 table 中创建了新的自定义字段,因为 asp.net 身份不包含 "Last Login Date"、"Registration Date" 和 "Profile Update Date".

在帐户注册过程中,我收到一条关于 datetime2 超出范围的错误消息。 3 个日期字段均为日期时间类型,并设置为 "Allow Null"。在此过程中,我只需要设置 "Registration Date" 的日期,其余的应该保持不变,但我不知道该怎么做?

此错误来自 "Last Login Date" 和 "Profile Update Date"。

创建用户函数

namespace Web_WebApp.Account
{
    public partial class Register : Page
    {
        protected void CreateUser_Click(object sender, EventArgs e)
        {

            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
            var user = new ApplicationUser() { UserName = UserName.Text, Email = Email.Text, FirstName = FirstName.Text, MiddleName = MiddleName.Text, LastName = LastName.Text, RegistrationDate = DateTime.Now };
            IdentityResult result = manager.Create(user, Password.Text );

            if (result.Succeeded)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                //string code = manager.GenerateEmailConfirmationToken(user.Id);
                //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");

                signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else 
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
    }
}

迁移文件

   namespace Web_WebApp.Migrations
    {
        using System;
        using System.Data.Entity.Migrations;

        public partial class NewDateFields : DbMigration
        {
            public override void Up()
            {
                AddColumn("dbo.User", "LastLoginDate", c => c.DateTime(nullable: true));
                AddColumn("dbo.User", "RegistrationDate", c => c.DateTime(nullable: true));
                AddColumn("dbo.User", "ProfileUpdateDate", c => c.DateTime(nullable: true));
            }

            public override void Down()
            {
                DropColumn("dbo.User", "ProfileUpdateDate");
                DropColumn("dbo.User", "RegistrationDate");
                DropColumn("dbo.User", "LastLoginDate");
            }
        }
    }

错误信息

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.Data.SqlClient.SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.

感谢您为解决我的问题所做的努力。

 SqlDataReader rdr = cmd.ExecuteReader();
 while (rdr.Read())
 {
    if (!(rdr["ProfileUpdateDate"] is DBNull))
    {
      employee.ProfileUpdateDate=Convert.ToDateTime(rdr["ProfileUpdateDate"]);
    }
 }
var user = new ApplicationUser() { 
    UserName = UserName.Text, 
    Email = Email.Text, 
    FirstName = FirstName.Text, 
    MiddleName = MiddleName.Text, 
    LastName = LastName.Text,
    RegistrationDate = DateTime.Now,
    ProfileUpdateDate = DBNull.Value,
    LastLoginDate = DBNull.Value
};

将列的数据类型从 datetime 更改为 datetime2

datetime 有一个范围从 1/1/1753 开始,如果提供的日期时间早于该时间将导致错误。

datetime2 从 1/1/0001 开始。

即将保存的 DateTime 不为空(可为空的 DateTime 后缀为 ?DateTime?),或作为 Nullable<DateTime>) ,并且可能具有值 DateTime.MinValue,即 1/1/0001。由于 DateTime 超出范围,这又会引发异常。

您遇到的错误是由于此字段的数据类型被声明为不可为 null 的 DateTime,因此您只需将其值初始化为某个有效日期即可解决您的问题。

var user = new ApplicationUser() { ... LastLoginDate = DateTime.now };

如果您出于任何原因不想初始化这些字段,您始终可以将它们声明为可为 null 的 DateTime,这样解决这个问题也很容易,因为您甚至不需要初始化它们。

public DateTime? LastLoginDate { get; set; }

...

AddColumn("dbo.AspNetUsers", "LastLoginDate", c => c.DateTime());