【问题标题】:Different timestamp retrieval from mongodb after inserting from C#从 C# 插入后从 mongodb 检索不同的时间戳
【发布时间】:2023-03-29 08:02:01
【问题描述】:

我正在使用 MongoDB,并且发现了奇怪的行为(至少对我而言)。从 C# 插入并从 MongoDB 检索时,我得到了时差。

我的实体:

[BsonId]
public ObjectId Id { get; set; }
public bool IsActive { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedTime { get; set; }
public string Name { get; set; }

使用以下代码插入时间戳:

public bool Insert(AccountCategories _input)
{
    _input = new AccountCategories();
    _input.CreatedBy = "super-admin";
    _input.CreatedTime = DateTime.Now;
    _input.Id = new ObjectId();
    _input.IsActive = true;
    _input.Name = "test-name";

    var _result = _repo.Insert(_input);

    return _result;
}
  • 插入的数据:{4/30/16 9:04:36 PM}
  • 检索数据:{4/30/16 2:04:36 PM}

我曾尝试通过添加 Bson 属性来修改实体,但它不起作用:

[BsonRepresentation(BsonType.Document)]
public DateTime CreatedTime { get; set; }

为什么会发生这种行为?我该如何解决这个问题?

【问题讨论】:

    标签: c# mongodb timestamp


    【解决方案1】:

    在本站和谷歌搜索期间更改关键字后,我设法找到了答案。

    根据 MongoDB 手册: https://docs.mongodb.org/manual/tutorial/model-time-data/

    时间默认为 UTC,这就是为什么我有 7 小时的差异(我不先看手册很糟糕) 所以我设法通过将 BsonAttribute 添加到 Datetime 来解决我的问题,如下所示:

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

    来源:Dealing with how MongoDB stores DateTime when used with Service Locator Pattern

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 2015-07-27
      • 2016-08-22
      • 1970-01-01
      • 2022-11-20
      • 2012-05-07
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多