'Emulating impact of SQL storage on C# DateTime

I have uncovered a unfortunate side-effect that storing and rehydrating a C# DateTime from a SQL Server datetime column alters it slightly, so that the equality operator is no longer valid.

For example, using EF:

FileInfo fi = new FileInfo("file.txt");
Entity.FileTimeUtc = fi.LastWriteTimeUtc;

we find that

(Entity.FileTimeUtc == fi.LastWriteTimeUtc)  // true

but if we save that entity and then reload it from SQL Server, we find that

(Entity.FileTimeUtc == fi.LastWriteTimeUtc)  // false

I understand that a process of rounding has happened here (if only by a few milliseconds) due to differing internal storage formats between the .NET DateTime and the SQL datetime.

What I am looking for is a process that will reliably emulate this conversion, and align native DateTime values to those which have been stored and rehydrated from a SQL datetime field, to make the equality test valid again.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source