tmm*_*360 6 c# reference driver mongodb
我有两个类,例如:
public class A
{
public string Id { get; set; }
public string Name { get; set; }
// Other properties...
}
public class B
{
public string Id { get; set; }
public ICollection<A> ReferredAObjects { get; set; }
// Other properties...
}
Run Code Online (Sandbox Code Playgroud)
我已经为A和B创建了带有BsonClassMap.RegisterClassMap()的类映射,因为它们被分开存储为相对集合.
当我尝试映射B时问题就开始了,因为我需要将A的集合映射为带有一些额外信息的外部文档的引用,所以在这种情况下我只需要映射id和名称.
如何为B创建一个类映射,仅在其中使用不同的映射?
BsonClassMap
不是你的解决方案,你应该IBsonSerializer
为B
类编写你的自定义我刚刚实现了该Serialize
方法,其Deserilze
工作方式相同。
public class BSerialzer : IBsonSerializer
{
public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
{
throw new NotImplementedException();
}
public object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
{
throw new NotImplementedException();
}
public IBsonSerializationOptions GetDefaultSerializationOptions()
{
throw new NotImplementedException();
}
public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
var b = (B)value;
bsonWriter.WriteStartDocument();
bsonWriter.WriteString("_id", b.Id);
bsonWriter.WriteStartArray("refs");
foreach (var refobj in b.ReferredAObjects)
{
bsonWriter.WriteString(refobj.Id);
}
bsonWriter.WriteEndArray();
bsonWriter.WriteEndDocument();
}
}
Run Code Online (Sandbox Code Playgroud)
对于下面对象的示例
var a0 = new A
{
Id = "0",
Name = "0",
};
var a1 = new A
{
Id = "1",
Name = "1",
};
var b = new B
{
Id = "b0",
ReferredAObjects = new Collection<A> { a0, a1 }
};
collection.Insert(b);
Run Code Online (Sandbox Code Playgroud)
将产生如下输出:
{
"_id" : "b0",
"refs" : [
"0",
"1"
]
}
Run Code Online (Sandbox Code Playgroud)
Sterilizer
请记住在程序启动时注册它:
BsonSerializer.RegisterSerializer(typeof(B), new BSerialzer());
Run Code Online (Sandbox Code Playgroud)