Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code first in entity framework set column to type datetime2 in sql server

I have a value

DateTime dt = DateTime.Parse("2015-10-12 14:24:40.582");

with it I do:

SomeEntity someEntity = new SomeEntity() 
{
    ID = 1, 
    ChangedOn = dt
};
context.SomeEntities.Add(someEntity);

What I found out: in database table the value stored is "2015-10-12 14:24:40.5830000"

I found it out manually with

SELECT CONVERT(datetime2, ChangedOn) FROM SomeEnititiesTable WHERE ID=1;

I load someEntity from database and do

bool ok = someEntity.ChangedOn.Equals(dt);

The problem is that ok == false when I expect ok == true. :|

How to make code first in entity framework generate column of type datetime2 instead of datetime in migrations?

like image 833
Developer Marius Žilėnas Avatar asked May 04 '16 10:05

Developer Marius Žilėnas


People also ask

What is the difference between datetime and DATETIME2 in SQL Server?

The main difference is the way of data storage: while in Datetime type, the date comes first and then time, in Datetime2, 3 bytes, in the end, represents date part!

What is DATETIME2 data type in SQL Server?

Defines a date that is combined with a time of day that is based on 24-hour clock. datetime2 can be considered as an extension of the existing datetime type that has a larger date range, a larger default fractional precision, and optional user-specified precision.

How insert DATETIME2 value in SQL Server?

Always use the format YYYY-MM-DD hh:mm:ss[. nnnnnnn] to insert the date into database. This is the default format that SQL Server uses. It is also the safe format and can be interpreted only in one way.


2 Answers

How to make code first in entity framework generate column of type datetime2 instead of datetime in migrations?

To specify the type of the column to use you can add the following attribute to the property ChangedOn of your model:

[Column(TypeName = "datetime2")]

Or if you are using the Fluent API then you can add this to your OnModelCreating of your DBContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // ...

    modelBuilder.Entity<someEntity>()
        .Property(p => p.ChangedOn)
        .HasColumnType("datetime2");

    // ...
}
like image 197
Nasreddine Avatar answered Oct 23 '22 17:10

Nasreddine


SOLUTION

1) Add a field ChangedOn2 with type of long.

2) Save dt.Ticks value to ChangedOn2.

3) Compare with

someEntity.ChangedOn2.Equals(dt.Ticks);
like image 26
Developer Marius Žilėnas Avatar answered Oct 23 '22 18:10

Developer Marius Žilėnas