Sto lavorando con un database MongoDB. So che quando inserisci un DateTime in Mongo, lo converte in UTC. Ma sto facendo un test unitario e il mio Assert sta fallendo.DateTime ToLocalTime non riuscito
[TestMethod]
public void MongoDateConversion() {
DateTime beforeInsert = DateTime.Now;
DateTime afterInsert;
Car entity = new Car {
Name = "Putt putt",
LastTimestamp = beforeInsert
};
// insert 'entity'
// update 'entity' from the database
afterInsert = entity.LastTimestamp.ToLocalTime();
Assert.AreEqual(beforeInsert, afterInsert); // fails here
}
Mi manca qualcosa di ovvio. Quando guardo nel debugger, posso vedere quella partita del datetime, ma l'asserzione dice ancora non lo fanno (ma lo fanno):
Result Message: Assert.AreEqual failed. Expected:<5/21/2015 8:27:04 PM>. Actual:<5/21/2015 8:27:04 PM>.
Tutte le idee che cosa sto facendo male qui?
EDIT:
mi è venuta in mente due possibili soluzioni, entrambi i quali mi richiedono di ricordarsi di fare qualcosa (che non è sempre la cosa migliore da fare affidamento su ...):
uno è quello di utilizzare un metodo di estensione per troncare qualsiasi DateTime che esce dal database:
public static DateTime Truncate(this DateTime dateTime) {
var timeSpan = TimeSpan.FromMilliseconds(1);
var ticks = -(dateTime.Ticks % timeSpan.Ticks);
return dateTime.AddTicks(ticks);
}
l'altro, dopo aver letto http://alexmg.com/datetime-precision-with-mongodb-and-the-c-driver/, è quello di etichettare qualsiasi DateTime nella classe POCO:
public class Car : IEntity {
public Guid Id { get; set; }
[BsonDateTimeOptions(Representation = BsonType.Document)]
public DateTime LastTimestamp { get; set; }
}
Vedi questo articolo che spiega MongoDB datetime precisione: http: // alexmg.com/datetime-precision-with-mongodb-and-the-c-driver/ –