Parisa
Parisa

Reputation: 51

Why EF-core code first makes DateTime2 instead of DateTime?

Im very new in EF-core code first, I want to be a variable in the form of a datetime,but its Datetime2. how can I fix it?

This is EF core , code first Approach and sql server 2017

public class MB_Message
{
    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int MessageID { get; set; }
    public DateTime? expireDateTime { get; set; }
    public string TypeName { get; set; }
    public bool IsForceLastSend { get; set; }
    public DateTime MessageDateTime { get; set; }
    public bool ReadOnce { get; set; }
    public string ExeCode { get; set; }
    [ForeignKey("MB_Queue")]
    public int QueueCode { get; set; }
    public int? UserID { get; set; }
    [ForeignKey("MB_MessageBody")]
    public int BodyID { get; set; }
    public bool Enable { get; set; }

}

Upvotes: 1

Views: 2545

Answers (2)

Red
Red

Reputation: 3267

To answer the "Why?"; because datetime is an old SQL Server specific data type that Microsoft recommend you avoid now. Maybe you need it to join on existing tables, but for new work datetime is not advised.

In comparison to datetime2(3), datetime is:

  • incompatible with other SQL systems so will need converting
  • takes up 1 more byte of data per row (duplicated for every index and RAM every time it's read)
  • offers no option for precision

Added to that, you probably want datetime2(0) in most cases, which is 2 bytes less than a datetime.

Upvotes: 1

vahid tajari
vahid tajari

Reputation: 1303

In OnModelCreating method of your dbcontext add following:

  protected override void OnModelCreating(ModelBuilder builder)
    {

        builder.Entity<MB_Message>()
            .Property(x=> x.MessageDateTime )
            .HasColumnType("datetime");
    }

Upvotes: 1

Related Questions