Entity Framework Code First Date field creation

后端 未结 8 2241
情歌与酒
情歌与酒 2020-11-30 23:13

I am using Entity Framework Code First method to create my database table. The following code creates a DATETIME column in the database, but I want to create a

相关标签:
8条回答
  • 2020-12-01 00:12

    I found this works in EF6 nicely.

    I created a convention for specifying my data types. This convention changes the default DateTime data type in the database creation from datetime to datetime2. It then applies a more specific rule to any properties that I have decorated with the DataType(DataType.Date) attribute.

    public class DateConvention : Convention
    {
        public DateConvention()
        {
            this.Properties<DateTime>()
                .Configure(c => c.HasColumnType("datetime2").HasPrecision(3));
    
            this.Properties<DateTime>()
                .Where(x => x.GetCustomAttributes(false).OfType<DataTypeAttribute>()
                .Any(a => a.DataType == DataType.Date))
                .Configure(c => c.HasColumnType("date"));
        }
    }
    

    Then register then convention in your context:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Add(new DateConvention());
        // Additional configuration....
    }
    

    Add the attribute to any DateTime properties that you wish to be date only:

    public class Participant : EntityBase
    {
        public int ID { get; set; }
    
        [Required]
        [Display(Name = "Given Name")]
        public string GivenName { get; set; }
    
        [Required]
        [Display(Name = "Surname")]
        public string Surname { get; set; }
    
        [DataType(DataType.Date)]
        [Display(Name = "Date of Birth")]
        public DateTime DateOfBirth { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-01 00:14

    I use following

        [DataType(DataType.Time)]
        public TimeSpan StartTime { get; set; }
    
        [DataType(DataType.Time)]
        public TimeSpan EndTime { get; set; }
    
        [DataType(DataType.Date)]
        [Column(TypeName = "Date")]
        public DateTime StartDate { get; set; }
    
        [DataType(DataType.Date)]
        [Column(TypeName = "Date")]
        public DateTime EndDate { get; set; }
    

    With Entity Framework 6 & SQL Server Express 2012 - 11.0.2100.60 (X64). It works perfectly and generates time/date column types in sql server

    0 讨论(0)
提交回复
热议问题