![](/img/trans.png)
[英]How do I query MongoDB using the C# driver with a query in string format?
[英]How can I tell the MongoDB C# driver to store all Nullable<Guids> in string format?
要將 Guid 序列化為字符串,我沒有問題,因為我使用的是以下代碼: https://stackoverflow.com/a/33258168/4148788
var pack = new ConventionPack { new GuidAsStringRepresentationConvention () };
ConventionRegistry.Register("GuidAsString", pack, t => t == typeof (MyClass));
public class GuidAsStringRepresentationConvention : ConventionBase, IMemberMapConvention
{
public void Apply(BsonMemberMap memberMap)
{
if (memberMap.MemberType == typeof(Guid))
{
var serializer = memberMap.GetSerializer();
var representationConfigurableSerializer = serializer as IRepresentationConfigurable;
if (representationConfigurableSerializer != null)
{
var reconfiguredSerializer = representationConfigurableSerializer.WithRepresentation(BsonType.String);
memberMap.SetSerializer(reconfiguredSerializer);
}
}
}
}
如果我嘗試為 Guid 做同樣的事情? 它不起作用
if (memberMap.MemberType == typeof(Guid?))
{
var serializer = memberMap.GetSerializer();
var representationConfigurableSerializer = serializer as IRepresentationConfigurable;
if (representationConfigurableSerializer != null)
{
var reconfiguredSerializer = representationConfigurableSerializer.WithRepresentation(BsonType.String);
memberMap.SetSerializer(reconfiguredSerializer);
}
}
此行始終為 null:
var representationConfigurableSerializer = serializer as IRepresentationConfigurable;
你如何處理可為空的Guids?
您需要重新配置當前的序列化程序還是可以直接替換它? 替換它會更簡單。
可空類型的 BSON 序列化器被包裝在裝飾器序列化器類型 ( NullableSerializer<>
) 中,我們只需檢查MemberType
是否為Nullable<Guid>
並為您的場景設置正確的序列化器。
查看以下約定代碼:
public class GuidAsStringRepresentationConvention : ConventionBase, IMemberMapConvention
{
public void Apply(BsonMemberMap memberMap)
{
if (memberMap.MemberType == typeof(Guid))
{
memberMap.SetSerializer(new GuidSerializer(BsonType.String));
}
else if (memberMap.MemberType == typeof(Guid?))
{
memberMap.SetSerializer(new NullableSerializer<Guid>(new GuidSerializer(BsonType.String)));
}
}
}
https://kevsoft.net/2020/06/25/storing-guids-as-strings-in-mongodb-with-csharp.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.