【问题标题】:How to pass Null value to datetime in ASP.Net Identity User Table?如何将 Null 值传递给 ASP.Net 身份用户表中的日期时间?
【发布时间】:2015-10-18 19:19:39
【问题描述】:

我已经在身份用户表中创建了新的自定义字段,因为 asp.net 身份没有“上次登录日期”、“注册日期”和“个人资料更新日期”等所有字段。

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

此错误来自“上次登录日期”和“个人资料更新日期”。

创建用户函数

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.

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

【问题讨论】:

    标签: c# asp.net datetime webforms asp.net-identity


    【解决方案1】:

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

    datetime 的范围从 1753 年 1 月 1 日开始,如果提供的日期时间早于此,则会导致错误。

    datetime2 从 0001 年 1 月 1 日开始。

    即将被保存的DateTime不为空(一个可以为空的日期时间会以?(DateTime?)或Nullable&lt;DateTime&gt;为后缀,并且可能具有DateTime.MinValue的值,这是 0001 年 1 月 1 日。由于 DateTime 超出范围,这反过来会引发异常。

    【讨论】:

      【解决方案2】:

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

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

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

      public DateTime? LastLoginDate { get; set; }
      

      ...

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

      【讨论】:

        【解决方案3】:
        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
        };
        

        【讨论】:

        • 我喜欢你的方法,因为它很干净,但我已经尝试过 DBNull.Value 并且它不允许我运行。
        【解决方案4】:
         SqlDataReader rdr = cmd.ExecuteReader();
         while (rdr.Read())
         {
            if (!(rdr["ProfileUpdateDate"] is DBNull))
            {
              employee.ProfileUpdateDate=Convert.ToDateTime(rdr["ProfileUpdateDate"]);
            }
         }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-20
          • 1970-01-01
          • 2015-07-09
          • 1970-01-01
          • 2017-10-08
          • 2021-04-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多