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?
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!
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.
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.
How to make code first in entity framework generate column of type
datetime2
instead ofdatetime
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");
// ...
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With