我正在尝试从 c# 中的 mongo 数据库中获取记录
mongodb集合中的数据:
{
id:0
parameter:"Unscheduled Demand"
remarks:"Formula Based"
value:89
}
问题:
id
属性未从 C# 中的数据反序列化。
C# 类结构:
public class children
{
[BsonId]
[BsonRepresentation(BsonType.Int32)]
public int id { get; set; }
public string parameter { get; set; }
public string remarks { get; set; }
public double value { get; set; }
}
这是发生的错误:
元素“id”与子类的任何字段或属性都不匹配
根据此处的文档https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/,
[BsonId]
属性定义应为Mongo的_id
元素映射哪个字段。如果您想使用名为“id”的字段,您应该删除此标签
public class children
{
[BsonRepresentation(BsonType.Int32)]
public int id { get; set; }
public string parameter { get; set; }
public string remarks { get; set; }
public double value { get; set; }
}
我的猜测是,在不删除属性的情况下,您仍然可以插入 Mongo,并看到有一个
_id
集
我们需要根据 C# 的官方 mongodb 文档手动识别身份属性
https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/
所做的改变
以前的班级结构
public class children
{
[BsonId]
[BsonRepresentation(BsonType.Int32)]
public int id { get; set; }
public string parameter { get; set; }
public string remarks { get; set; }
public double value { get; set; }
}
当前班级结构
public class children
{
[BsonRepresentation(BsonType.Int32)]
public int id { get; set; }
public string parameter { get; set; }
public string remarks { get; set; }
public double value { get; set; }
}
额外变更
Startup.cs
BsonClassMap.RegisterClassMap<children>(cm =>
{
cm.MapProperty(c => c.id);
cm.MapProperty(c => c.parameter);
cm.MapProperty(c => c.remarks);
cm.MapProperty(c => c.value);
});
进行上述更改解决了我的问题
这些更改(特别是
BsonClassMap.RegisterClassMap
)对于覆盖“识别 Id 字段或属性”部分中的 C# 序列化约定是必要的:
注意
默认约定将发现名为
、Id
或id
的公共属性或字段。通常不需要用属性来修饰该字段或显式映射它。_id