How to change EF6 to create Datetime fields as datetime2

Asked

Viewed 132 times

0

I am working with **EF6 Code-first", SQL-Server database.

I came across the following error, when saving an object with Datetime property.

The Conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

Searching, I found that EF6 by default creates the Type properties Datetime of C#, like the guy datetime of Sql-Server.

I did some research to understand the difference, even created a question about it here in the stack datetime vs datetime2. which is the best?, in the colleague’s reply, he highlighted the suggestion in the microsoft documentation itself, indicating the use of datetime2. As mentioned below..

Use the data types time, date, datetime2 and datetimeoffset for the new job. These types are in accordance with the standard SQL. They are more portable. time, datetime2 and datetimeoffset provide more accuracy of seconds. datetimeoffset is time zone compatible for globally deployed applications. Source: https://docs.microsoft.com/pt-br/sql/t-sql/data-types/datetime-transact-sql

Based on that, I want to know how to get EF6 to use the datetime2, without having to configure the property property. Which would be as follows:

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

I want a global setup.

  • What version of your bank?

  • 1

    @Virgilionovic is the V12 of Azure

2 answers

1

1


In his Context you can configure so that all type properties DateTime are datetime2. For that it is necessary to give one override the method OnModelCreating the code would look like this:

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

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {            
        modelBuilder.Properties<DateTime>()
            .Configure(p => p.HasColumnType("datetime2"));
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.