Я только что столкнулся с этим во время использования сеанса SQLite в памяти.Я отладил его и заметил, что свойства DateTimes «Миллисекунды» и «Вид» различаются (тип «Utc» и «Не определено»).
Моя реализация в соответствии с предложением Коула W:
class DateTimeEqualityComparer : IEqualityComparer
{
private TimeSpan maxDifference;
public DateTimeEqualityComparer(TimeSpan maxDifference)
{
this.maxDifference = maxDifference;
}
public bool Equals(object x, object y)
{
if (x == null || y == null)
{
return false;
}
else if (x is DateTime && y is DateTime)
{
var dt1 = (DateTime)x;
var dt2 = (DateTime)y;
var duration = (dt1 - dt2).Duration();
return duration < maxDifference;
}
return x.Equals(y);
}
public int GetHashCode(object obj)
{
throw new NotImplementedException();
}
}
Ваш тест спецификации становится примерно таким:
var maxDifference = TimeSpan.FromSeconds(1);
...
new PersistenceSpecification<Blah>(Session)
...
.CheckProperty(c => c.Created, System.DateTime.Now,
new DateTimeEqualityComparer(maxDifference))