【问题标题】:How to insert current date and time to SQL Server table that has a column with DateTime type?如何将当前日期和时间插入到具有 DateTime 类型列的 SQL Server 表中?
【发布时间】:2022-01-06 13:08:22
【问题描述】:

我正在我的 ASP.NET Core 项目中工作,并尝试在新用户注册时添加当前注册日期和时间。为此,我使用了以下代码。这是注册ActionResult的一部分:

DateTime currentDate = DateTime.Now;
var user = new AppUser() {
    department = registerModel.department,
        creationDate = registerModel.creationDate = currentDate,
        isAdmin = registerModel.isAdmin,
        isManager = registerModel.isManager,
        isActive = registerModel.isActive,
        canEdit = registerModel.canEdit,
        canDelete = registerModel.canDelete,
        canSendMessage = registerModel.canSendMessage,
        canSeeNotification = registerModel.canSeeNotification
};

当我按下注册按钮时,显示以下错误:

处理请求时发生未处理的异常。 InvalidCastException:System.DateTime 类型的字段必须是 字符串、数组或 ICollection 类型。 System.ComponentModel.DataAnnotations.MaxLengthAttribute.IsValid(对象 值)

如何生成 SQL Server 接受的格式,同时将该对象保留为 DateTime 对象?

更新:

public class AppUser: IdentityUser < int > {
        [Display(Name = "Department")]
        [Required(ErrorMessage = "Please enter depertment")]
        [MaxLength(20)]
        public string department {
            get;
            set;
        }
        [Display(Name = "Creation date")]
        [DataType(DataType.DateTime)]
        [MaxLength(100)]
        public DateTime creationDate {
            get;
            set;
        }
        [Required]
        //[Range(0, 1)]
        public bool isAdmin {
            get;
            set;
        }
        [Required]
        //[Range(0, 1)]
        public bool isManager {
            get;
            set;
        }
        [Required]
        //[Range(0, 1)]
        public bool isActive {
            get;
            set;
        }
        [Required]
        //[Range(0, 1)]
        public bool canEdit {
            get;
            set;
        }
        [Required]
        //[Range(0, 1)]
        public bool canDelete {
            get;
            set;
        }
        [Required]
        //[Range(0, 1)]
        public bool canSendMessage {
            get;
            set;
        }
        [Required]
        //[Range(0, 1)]
        public bool canSeeNotification {
            get;
            set;
        }

【问题讨论】:

  • 您使用代码优先还是数据库优先方法?
  • @DannyBoy 我正在使用 CodeFirst。
  • 您使用的是哪个 .NET Core 版本?能否请您提供该物业的型号代码?试试下面的 Serges 回答。 :D
  • 你能发布AppUser类吗?
  • 我更新了主要问题

标签: c# asp.net-core datetime .net-core


【解决方案1】:

试试这个

creationDate  = currentDate,
isAdmin = registerModel.isAdmin,
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    相关资源
    最近更新 更多