如何使用官方的MongoDB C#驱动程序将BsonDocument转换为强类型对象? [英] How to convert a BsonDocument into a strongly typed object with the official MongoDB C# driver?
问题描述
出于单元测试的目的,我想测试类映射,而无需将文档写入MongoDB数据库中.为了处理特殊情况,例如循环的父/子引用和只读属性,我使用了BsoncClassMap.RegisterClassMap< MyType>(...)
和一些自定义映射,这些自定义映射覆盖了默认的AutoMap();
生成的映射.
For unit testing purposes, I'd like to test my class mappings without reading and writing documents into the MongoDB database. To handle special cases such as circular parent / child references and read only properties, I've used BsoncClassMap.RegisterClassMap< MyType>(...)
with some custom mappings overriding the default AutoMap();
generated mappings.
有人知道如何在不往返数据库的情况下将BsonDocument转换为所需的强类型对象吗?在往返数据存储区时,驱动程序正在执行此操作.我的目标是使用与MongoDB C#驱动程序内部使用的逻辑相同,以测试从C#域对象到BsonDocument的序列化.
Does anyone know how to convert a BsonDocument into the desired strongly typed object without making a round trip to the database? The driver is doing this when going to and from the data store. My goal would be to use the same logic that the MongoDB C# driver is using internally to test the serialization to / from a C# domain object into a BsonDocument.
我能够使用Bson扩展方法ToBsonDocument()
将C#对象转换为BsonDocument?我所缺少的是与过程相反的过程-本质上是BsonDocument.ToObject< MyType>();
.
I'm able to use the Bson extension method ToBsonDocument()
to convert a C# object into a BsonDocument? The piece that I'm lacking is the reverse of the process - essentially a BsonDocument.ToObject< MyType>();
.
最新版本的官方MongoDB C#驱动程序是否有可能?似乎应该-我想知道我是否只是盲目而错过了明显的事物.
Is this possible with the latest version of the official MongoDB C# driver? It seems like it should be - I'm wondering if I'm just blind and am missing the obvious.
推荐答案
MongoDB驱动程序确实提供了一种从Bson反序列化为您的类型的方法.可以在MongoDB.Bson.dll
命名空间中的MongoDB.Bson.dll
中找到BsonSerializer
.
The MongoDB Driver does provide a method for deserializing from Bson to your type. The BsonSerializer
can be found in MongoDB.Bson.dll
, in the MongoDB.Bson.Serialization
namespace.
您可以使用BsonSerializer.Deserialize<T>()
方法.一些示例代码将是
You can use the BsonSerializer.Deserialize<T>()
method. Some example code would be
var obj = new MyClass { MyVersion = new Version(1,0,0,0) };
var bsonObject = obj.ToBsonDocument();
var myObj = BsonSerializer.Deserialize<MyClass>(bsonObject);
Console.WriteLine(myObj);
其中MyClass
定义为
public class MyClass
{
public Version MyVersion {get; set;}
}
我希望这会有所帮助.
这篇关于如何使用官方的MongoDB C#驱动程序将BsonDocument转换为强类型对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!