【问题标题】:Unable to read TimeZoneInfo from MongoDB document无法从 MongoDB 文档中读取 TimeZoneInfo
【发布时间】:2018-10-15 10:23:57
【问题描述】:

我有一个包含 TimeZoneInfo 属性的 C# 对象。我可以将它保存到 MongoDB。但是当我把它取回来时,它是空的。所有其他属性都已正确映射。

我的DTO 结构如下所示;还有其他东西,但我只提到了几个属性:

public class TerminalDto
{
    public string Code { get; set; }
    public GeographyDto Geography { get; set; }
    public GeoCoordinateDto GeoCoordinate { get; set; }
    public TimeZoneInfo TimeZone { get; set; }
}

我的 mongo 文档存储为:

{
    "_id": "5bc4601d5d46855e6c8a337b",
    "Code": "AK",
    "Geography": {
        "City": "Akron",
        "State": {
            "Name": "OHIO",
            "Code": "OH"
        }
    },
    "GeoCoordinate": {
        "Latitude": "40.97665",
        "Longitude": "-81.464607"
    },
    "TimeZone": {
        "_id": "Eastern"
    }
}

当我读回它时,我的DTO 属性被填充,除了TimeZone info

{
    "_id": "5bc4601d5d46855e6c8a337b",
    "Code": "AK",
    "Geography": {
        "City": "Akron",
        "State": {
            "Name": "OHIO",
            "Code": "OH"
        }
    },
    "GeoCoordinate": {
        "Latitude": "40.97665",
        "Longitude": "-81.464607"
    },
    "TimeZone": {} // Empty Here
}

我的终端存储库是这样的。

public class TerminalRepository
{
    public TerminalRepository(IMongoConnectionFactory mongoConnectionFactory)
    {
        this.collection = mongoConnectionFactory.GetCollection<TerminalDto>();
    }

    private readonly IMongoCollection<TerminalDto> collection;

    public async Task<IEnumerable<TerminalDto>> GetTerminals(int scenarioId)
    {
        var filter = Builders<TerminalDto>.Filter.Eq(t => t.ScenarioId, scenarioId);
        var dtos = (await this.collection.FindAsync(filter)).ToList();
    }
}

我尝试搜索 MongoDB 官方文档,但找不到任何与存储 TimeZoneInfo 相关的信息。

我该如何解决?

【问题讨论】:

标签: c# mongodb timezone mongodb-query


【解决方案1】:

您不应将TimeZoneInfo 类序列化到文档中,而应仅将.Id 属性序列化。有很多方法可以做到这一点,但一种方法是使用“伙伴属性”,例如:

public class TerminalDto
{
    // ... your other properties ...

    public string TimeZoneId { get; set; }

    [BsonIgnore]
    public TimeZoneInfo TimeZone
    {
        get
        {
            return TimeZoneInfo.FindSystemTimeZoneById(this.TimeZoneId);
        }

        set
        {
            this.TimeZoneId = value.Id;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    相关资源
    最近更新 更多