0

I am using entity framework and storing a DateTime with kind as 'Utc'.

For unit testing puroposes when retrieving this DateTime from the database it is coming out with an 'unspecified' kind and different ticks value.

I understand that Entity Framework cannot automatically assign it the Utc kind but I cannot understand why it would come out with a different ticks value.

This is a problem since I am using Mspec to test the retrieved value against the one that was put in using

result.Date.ShouldEqual(retrievedDate)

This statement is returning false since the kinds on each value are different. I also tried:

DateTime.Compare(result.Date, retrievedDate)

but this returned false since the ticks value is different.

FLICKER
  • 6,439
  • 4
  • 45
  • 75
jjharrison
  • 841
  • 4
  • 19
  • 33
  • Are you using [**`sysutcdatetime()`**](https://msdn.microsoft.com/en-us/library/bb630387.aspx) from sql server? [**`datetime`**](https://msdn.microsoft.com/en-us/library/ms187819.aspx) and [**`datetime2(7)`**](https://msdn.microsoft.com/en-us/library/bb677335.aspx) have different levels of precision. Could this be causing the mismatch? – SqlZim Feb 06 '17 at 17:30
  • [This answer](http://stackoverflow.com/questions/4648540/entity-framework-datetime-and-utc) can help you with the `DateTimeKind` problem, but SqlZim is right - you need a `datetime2` in SQL if you want the full range and precision of a `DateTime` in .NET. – Matt Johnson-Pint Feb 06 '17 at 19:12
  • If all your dates are stored as Utc, you could use my answer to [DateTime.Kind set to unspecified, not UTC, upon loading from database](http://stackoverflow.com/questions/40205893/datetime-kind-set-to-unspecified-not-utc-upon-loading-from-database/40349051#40349051) – Ivan Stoev Feb 06 '17 at 19:15

1 Answers1

0

I have fixed the issue by using a DateTimeOffset property instead of a DateTime.

Microsoft state that:

DateTimeOffset should be considered the default date and time type for application development.

jjharrison
  • 841
  • 4
  • 19
  • 33