【问题标题】:CosmosDB MongoDB-API omitting enums if value equals zero如果值为零,则 CosmosDB MongoDB-API 省略枚举
【发布时间】:2019-08-01 09:20:49
【问题描述】:

目前,我们正在使用 MongoDB API 将一个项目从 MongoDB 迁移到 CosmosDB。在数据模型中,我们有时会使用枚举并将它们(表示为 int,使用默认序列化程序)存储在数据库中。

在遇到极少数情况下的问题后,我们观察到,当枚举值等于 0 时,枚举不会存储在 CosmosDB 中。(MongoDB 在这种情况下存储它们)

有没有办法强制 CosmosDB 存储这些条目?重组程序将是一项重大工作,应该避免。

例子:

public enum EPower
{
    mW = 0,
    W = 1,
    kW = 2
}

插入方式

var obj = new ContainingType();
// client is MongoClient
var db = client.GetDatabase(MyDB);
var collection = db.GetCollection<ContainingType>(MyCollection);
await collection.InsertOneAsync(obj);

将存储在 MongoDB 中:

{
  "SomeProp": "foo",
  "Power": 0
}

在 CosmosDB 中:

{
  "SomeProp": "foo"
}

我们还尝试通过 ConventionPacks 强制使用不同的枚举表示

ConventionRegistry.Register("EnumStrings",
                        new ConventionPack { new EnumRepresentationConvention(BsonType.String)  },
                        t => true);

但是如果它们的值为0,枚举仍然会被省略。(除了这种存储不好)

【问题讨论】:

  • 我猜,使用 0 表示“无” - 条目,让所有“严重”条目的值 > 0 是没有选择的?
  • 不是这样,否则问题就解决了

标签: c# enums azure-cosmosdb azure-cosmosdb-mongoapi


【解决方案1】:

没有理由存储为Enum。只需使用一个类:

public class EPower
{
    public int mW = 0;
    public int W = 1;
    public int kW = 2;
}

【讨论】:

  • 如前所述,这是一个现有的应用程序,依赖于枚举并使定义在外部可用
  • 很好,所以在枚举和 dto 之间创建一个映射类?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多