C# / MongoDB - 将枚举字典键序列化为字符串

rya*_*ano 2 c# enums dictionary mongodb

我正在尝试序列化字典的字典,其中父字典的键为 type enum,子字典的键为 type DateTime。在尝试插入我的收藏时,我遇到了

使用 DictionaryRepresentation.Document 时,键值必须序列化为字符串

我读过讨论enuminto序列化的论坛string,但是根据当前的模型定义,我不确定如何使用此方法。

当前使用的两个字典模型只是该类的实现Dictionary

指数值

{
    public class IndexValues : Dictionary<Index, DateDictionary> { }
}
Run Code Online (Sandbox Code Playgroud)

日期字典

public class DateDictionary : Dictionary<DateTime, double>
    {
        public double AsOf(DateTime d)
        {
            DateTime date = d;
            while (date >= Keys.Min())
            {
                if (TryGetValue(date, out var value))
                {
                    return value;
                }
                date = date.AddDays(-1);
            }

            throw new Exception($"The dictionary doesn't have a value for any date less than or equal to {d}.");
        }
    }
Run Code Online (Sandbox Code Playgroud)

指数

public enum Index
    {
        SPX,
        NDX
    }
Run Code Online (Sandbox Code Playgroud)

我通过简单地实例化两个类的新实例并在所需类型中添加值来将值添加到主程序中的字典中。

IndexValues indexRecords = new IndexValues();

...

var enumHead = (Index)Enum.Parse(typeof(Index), header[l]); // header is simply a list of strings

...

DateDictionary dateDict = new DateDictionary();

var date = Convert.ToDateTime(dataLine[j]); // dataLine is simply a list of strings
var value = Convert.ToDouble(dataLine[k]);

if (indexRecords.ContainsKey(enumHead))
    {
        indexRecords[enumHead].Add(date, value);
    }
    else
    {
        dateDict.Add(date, value);
        indexRecords.Add(enumHead, dateDict);
    }
Run Code Online (Sandbox Code Playgroud)

我尝试在模型定义中定义键和值,并使用[BsonRepresentation(BsonType.String)]和值以及for ,但仍然遇到相同的问题enumDateTime[BsonDictionaryOptions(DictionaryRepresentation.Document)]DateDictionary

在这种情况下我错过了什么,正确的方向是什么?作为参考,我使用的是 C# 驱动程序 v2.8.1。

rya*_*ano 7

事实证明我需要两个序列化器而不是一个。我在全球范围内定义了这些,并且能够毫无问题地插入。

BsonSerializer.RegisterSerializer(new EnumSerializer<Index>(BsonType.String));
BsonSerializer.RegisterSerializer(new DateTimeSerializer(DateTimeKind.Local, BsonType.String));
Run Code Online (Sandbox Code Playgroud)