我正在尝试使用 MongoDB C# 驱动程序并将对象存储到 MongoDB 集合,并在我的模型上使用 GeoJSON .Net 库,而不是 MongoDB GeoJSON 类(我不希望在我的模型上实现特定的细节,并且作为两者都应该使用 GeoJSON 标准,属性名称应该匹配)。
当我尝试将模型保存到集合中时,出现以下错误:
An error occurred while serializing the Coordinates property of class GeoJSON.Text.Geometry.LineString: Creator map for class GeoJSON.Text.Geometry.Position has 3 arguments, but none are configured.
阅读文档 - https://www.mongodb.com/docs/drivers/csharp/current/fundamentals/serialization/class-mapping/#mapping-with-constructors - 看来我需要配置 BSON 类映射,我已按如下方式完成,但是我仍然收到该错误消息。在为 MongoDB 序列化注册类方面我是否遗漏了其他内容?我对此的理解是否不正确并且MapCreator不是用于此目的的映射方法?
BsonClassMap.RegisterClassMap<Position>(cm =>
{
cm.AutoMap();
cm.MapCreator(p => new Position(p.Longitude, p.Latitude, p.Altitude));
});
编辑:附加代码
public class PaddockView : IEntity
{
public Guid Id { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public Guid FarmId { get; set; }
public string Name { get; set; } = "";
public string Description { get; set; } = "";
public PaddockType PaddockType { get; set; }
public Polygon Geometry { get; set; } = new (new List<LineString>
{
new LineString(new List<Position>
{
new Position(0, 0),
new Position(0, 1),
new Position(1, 1),
new Position(1, 0),
new Position(0, 0) // Closing the loop (same as the first position)
})
});
}
以及 mongo 初始化代码:
BsonClassMap.TryRegisterClassMap<Position>(cm =>
{
cm.AutoMap();
cm.MapCreator(p => new Position(p.Longitude, p.Latitude, p.Altitude));
});
// Determine the GUID serialization mode
var objectSerializer = new ObjectSerializer(ObjectSerializer.AllAllowedTypes);
BsonSerializer.TryRegisterSerializer(objectSerializer);
BsonSerializer.TryRegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
var mongoUrl = MongoUrl.Create(connectionString);
var client = new MongoClient(mongoUrl);
var db = client.GetDatabase(mongoUrl.DatabaseName);
// get collection and save object occurs after this.
必须是更通用的方法,但以下解决了您的问题:
BsonClassMap.RegisterClassMap<Position>(cm =>
{
cm.AutoMap();
var ctors = typeof(Position).GetConstructors();
cm.UnmapConstructor(ctors.Last()); // last is about ctor with string arguments
});
var objectSerializer = new ObjectSerializer(type =>
ObjectSerializer.DefaultAllowedTypes(type) || type == typeof(Position));
BsonSerializer.RegisterSerializer(objectSerializer);
var res = obj.ToBsonDocument();
此方法从考虑的构造函数中删除了带有字符串参数的有问题的构造函数。为了避免此错误,构造函数应该具有与类中的属性相同的参数,并且名称和类型匹配(在这种情况下,类型不相同)。我认为有一个更优雅的方法,但我没有花这么长时间来快速完成