How to change EF6 to create DateTime fields like datetime2

0

I'm working with EF6 Code-first, SQL-Server database.

I encountered the following error when saving an object with DateTime property.

  

The conversion of a datetime2 data type to a datetime result in an out-of-range value.   ↵The statement has been terminated.

Searching, I have found that EF6 by default creates the DateTime properties of C # , such as datetime Sql-Server .

I did some research to understand the difference, I even asked a question about it here in the stack datetime vs datetime2. which one is the best? , in his colleague's response, he highlighted the suggestion in Microsoft's own documentation, indicating the use of datetime2. As I mention below ..

  

Use the time, date, datetime2, and datetimeoffset data types for the new job. These types conform to standard SQL. They are more portable. time, datetime2, and datetimeoffset provide more precision of seconds. datetimeoffset is compatible with time zone for globally deployed applications. Source: link

Based on this, I want to know how to get EF6 to use datetime2 , without having to set ownership of the property. That would be as follows:

Property(m => m.Created)
        .HasColumnName("Created")
        .HasColumnType("datetime2")
        .IsRequired();

I want a global configuration.

    
asked by anonymous 06.04.2018 / 15:37

2 answers

1

In your Context you can configure all properties of type DateTime to be datetime2 . For this it is necessary to give a override method OnModelCreating the code would be like this:

public class MyContext : DbContext
{
    public MyContext()
    {}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {            
        modelBuilder.Properties<DateTime>()
            .Configure(p => p.HasColumnType("datetime2"));
    }
}
    
06.04.2018 / 15:43
1

In my case, I set this in the OnModelCreating method by adding this line:

modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));

It was an answer to this question in the OS (I did not accept it, but the one that helped me): link

    
06.04.2018 / 15:43