如何在ASP中传递Null值给datetime.网络身份用户表

本文关键字:datetime 值给 网络 身份 用户 Null ASP | 更新日期: 2023-09-27 18:05:17

我已经在身份用户表中创建了新的自定义字段,因为asp.net身份没有所有字段,如"最后登录日期","注册日期"answers"配置文件更新日期"。

在帐户注册期间,我得到一个关于datetime2超出范围的错误消息。所有3个日期字段都是日期时间类型,并设置为"允许Null"。在这个过程中,我只需要设置"注册日期"的日期,其余的应该保持不变,但我不知道我怎么做?

此错误来自"上次登录日期"answers"配置文件更新日期"。

创建用户函数

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.

我很感激你为解决我的问题所做的努力。

如何在ASP中传递Null值给datetime.网络身份用户表

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

datetime的取值范围是从1/1/1753开始的,如果提供的日期时间早于此,将导致错误。

datetime2开始于1/1/0001

要保存的DateTime不为空(可为空的DateTime将以? (DateTime?)或Nullable<DateTime>作为后缀),并且可能具有值DateTime.MinValue,即1/1/0001。这反过来会抛出一个异常,因为DateTime超出了范围。

您所面临的错误是由于该字段的数据类型被声明为不可空的DateTime,因此您可以解决您的问题,只需将其值初始化为一些有效的日期。

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

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

public DateTime? LastLoginDate { get; set; }

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

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
};
 SqlDataReader rdr = cmd.ExecuteReader();
 while (rdr.Read())
 {
    if (!(rdr["ProfileUpdateDate"] is DBNull))
    {
      employee.ProfileUpdateDate=Convert.ToDateTime(rdr["ProfileUpdateDate"]);
    }
 }