使用 C# monogDb 驱动程序时向 mongoDb 添加字典<DateTime,T>

问题描述 投票:0回答:1

当前我正在尝试使用 c# monogDb 驱动程序将具有属性 Dictionary 的对象添加到 mongoDb。

在项目中我有很多相关的遗留代码,所以我不能轻易地将字典更改为任何其他类型。字典是我的项目中相当常见的数据类型,因此在所有属性之上添加单独的标签来定义序列化器并不是一个好的选择。我想找到一种序列化字典的通用方法。

我已阅读以下相关文章,并尝试应用约定,但这似乎给我带来了子序列化器的问题。添加项目时出现以下错误:System.InvalidOperationException:ValueFactory 尝试访问此实例的 value 属性。我不知道问题到底是什么或如何解决。

c# mongodb mongodb-.net-driver
1个回答
0
投票

根据@Poul Bak的建议,该问题可以通过以下方式解决:

作为示例,我将使用类 Item

public class Item {
     public Dictionary<DateTime, AnotherItem> Dictionary {get;set;}
}

创建价值转换器

    public class DateTimeDictionaryConverter<T>: ValueConverter<Dictionary<DateTime, T>, string> {

    public DateTimeDictionaryConverter() : base(
        v => ConvertToJson(v),
        v => ConvertFromJson(v))
    {
    }

    private static string ConvertToJson(Dictionary<DateTime, T> dict)
    {
        return JsonSerializer.Serialize(dict);
    }

    private static Dictionary<DateTime, T> ConvertFromJson(string value)
    {
        return JsonSerializer.Deserialize<Dictionary<DateTime, T>>(value);
    }
}

然后将转换器添加到数据库上下文中的正确实体

modelBuilder.Entity<Item>().Property(i => i.Dictionary).HasConversion(new DateTimeDictionaryConverter<OtherItem>())

这可行,唯一剩下的缺点是必须使用字典为每个项目添加值转换器

© www.soinside.com 2019 - 2024. All rights reserved.