Reputation: 6119
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?
Upvotes: 7
Views: 3428
Reputation: 6119
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);
Upvotes: 1
Reputation: 37848
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");
// ...
}
Upvotes: 7