簡體   English   中英

Mongodb C#驅動程序和ISODate

[英]Mongodb c# driver and ISODate

我通過了以下測試:

namespace MongoDateTest
{

    [TestFixture]
    public class DateTesting
    {
        public class TestEntity
        {
            public string Id { get; set; }
            public string StringTest { get; set; }
            public DateTime DateTest { get; set; }

        }
        [Test]
        public void MongoDateConversion()
        {
            const string connectionString = "mongodb://localhost";
            var client = new MongoClient(connectionString);
            var server = client.GetServer();
            var database = server.GetDatabase("test");
            var collection = database.GetCollection<TestEntity>("entities");
            var entity = new TestEntity { 
                   Id = "1", 
                   StringTest = "Test",
                   DateTest = new DateTime(2013, 10, 13) //this is the date
            };
            collection.Save(entity);
            var id = entity.Id;
            var query = Query<TestEntity>.EQ(e => e.Id, id);
            var entityNew = collection.FindOne(query);
            Assert.AreEqual(entityNew.Id, entity.Id);
            Assert.AreEqual(entity.StringTest, entityNew.StringTest);

            //Assert.AreEqual(entity.DateTest,entityNew.DateTest);
            // This gives one day error:
            //  Expected: 2013-10-13 00:00:00.000
            //  But was:  2013-10-12 22:00:00.000
            //Assert.AreEqual(entity.DateTest.ToLocalTime(),entityNew.DateTest.ToLocalTime());
            // This gives a 2 hours error.
            //   Expected: 2013-10-13 02:00:00.000
            //   But was:  2013-10-13 00:00:00.000
            Assert.AreEqual(entity.DateTest, entityNew.DateTest.ToLocalTime());
        }
    }
 }

如果我取消任何Asserts.AreEqual的注釋,則會收到錯誤消息(在下面注釋)。

保存的實體為:

{
"_id" : "1",
"StringTest" : "Test",
"DateTest" : ISODate("2013-10-12T22:00:00Z")
 }

我知道這可能與ISODate和UTC有關(我在UTC + 1中),但是我有點生氣,因為我的日期保存在集合中有一天的差異,並且要求我在每次獲取一些數據時都轉換為localTime與日期。

此行為的原因是什么,有什么辦法可以避免呢?

在大多數情況下,您希望將UTC日期時間存儲在數據庫中,因此DateTime應該構造為:-

DateTest = new DateTime(2013, 10, 13, 0, 0, 0, DateTimeKind.Utc) //this is the date

這樣,您的第一個評論單元測試就可以通過了。

如果不指定DateTimeKind ,則可能要碰碰運氣。 MongoDB似乎假定它是本地的,並將其轉換為數據庫中的UTC。

還請注意,MongoDB DateTime值的精度低於.NET DateTime值。 如果要存儲任意的DateTime值並以仍然匹配的方式返回它們,則需要在存儲它們之前將它們四舍五入到最接近的毫秒數。

如果您確實想存儲本地時間,建議您從DateTime切換到DateTimeOffset並將其序列化為UTC DateTime的長Tick值和偏移量的值。

請注意,除非您存儲在獲取DateTime值時計算的偏移量,否則用於轉換為LocalTime的.NET方法本質上是無用的,因為它們不知道夏令時開始的時間,也不知道DateTime值位於哪個區域從。 總的來說,.NET DateTime處理有很多不足之處,並且包含許多誤導性方法,這些方法聲稱有幫助,但實際上沒有幫助。

您也可以在模型中執行此操作。 公共類TestEntity

{
    public string Id { get; set; }

    public string StringTest { get; set; }

    [BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
    public DateTime DateTest { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM