如何使用 EF Core、Code First 将自动分配的 DateTime2 数据类型更改为 DateTime?

How to change automatically assigned DateTime2 data type to DateTime with EF Core, Code First?

我正在使用 ASP.NET Core 2.2.4 和 EF Core Code First 迁移方法编写一个新应用程序。我编写了我的领域模型并通过包管理器控制台更新了数据库,但这导致我在我的领域模型中拥有的所有 DateTime 属性都被创建为 DateTime2(7) table 列。 我只需要日期时间。

首先,我试图通过在 SQL 服务器中编写一个查询来更改数据类型来更改它,它确实在 SQL 服务器内部显示它已更改为日期时间。但是当我在 Visual Studio 中打开 SQL 服务器对象资源管理器时,它仍然将该列显示为 datetime2(7) 类型。

之后我尝试将以下注释添加到 DateTime 属性 [列(类型名称 = "DateTime")]。之后我添加了一个迁移并通过包管理器控制台更新了数据库。这没有任何效果。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace GYM.CoreApp.WebUI.Models
{
    public class Employee
    {
        [Key]
        public int EmployeeId { get; set; }

        [Required]
        [MaxLength(100), MinLength(2)]
        [Display(Name ="First Name")]
        public string FirstName { get; set; }

        [Required]
        [MaxLength(100), MinLength(2)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required]
        [Column(TypeName = "DateTime")]
        [Display(Name = "Date of birth")]
        public DateTime DateOfBirth { get; set; }

        [Required]
        [MaxLength(13), MinLength(13)]
        [Display(Name = "EMBG")]
        public string EMBG { get; set; }

        [Required]
        [MaxLength(200), MinLength(2)]
        [Display(Name = "Home address")]
        public string Address { get; set; }

        [Required]
        [MaxLength(13), MinLength(9)]
        [Display(Name = "Phone number")]
        public string PhoneNumber { get; set; }

        [Required]
        [Display(Name = "Salary per month")]
        public int SalaryPerMonth { get; set; }

        [Required]
        [Column(TypeName = "DateTime")]
        [Display(Name = "Date when joined company")]
        public DateTime DateWhenJoined { get; set; }

        [Required]
        [Display(Name = "Still Employed")]
        public bool StillEmployed { get; set; }

    }
}

确保安装 Microsoft.EntityFrameworkCore.SqlServer。然后使用TypeName属性:

[Column(TypeName = "datetime")]

如果 SQL 服务器对象资源管理器仍然显示 datetime2,您可能需要退出并 re-open Visual Studio.

此答案未提供如何强制 EF Core 使用 datetime 而不是 datetime2 创建列,因为您不应该这样做。

SQL 服务器 datetime2datetime 之间的主要区别是可以使用的精度和更宽的日期范围。 System.DateTime 的默认值为 datetime2,当您使用兼容的客户端时没有理由不使用它。

System.DateTime 直接映射到 SQL 服务器 datetime2 并且是 Microsoft 推荐的用于在 SQL 服务器中存储 System.DateTime 的数据类型。

还值得注意的是,datetime2(7)datetime 占用的 space 少一个字节,并提供更高的精度。

参见 MSDN SQL Server datetime

上的注释