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

2

7

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?

Delphinus answered 4/5, 2016 at 10:33 Comment(0)
D
1

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);
Delphinus answered 4/5, 2016 at 12:18 Comment(0)
D
7

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");

    // ...
}
Decompose answered 4/5, 2016 at 12:39 Comment(0)
D
1

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);
Delphinus answered 4/5, 2016 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.