问题描述
我正在使用MongoDB C#驱动程序版本2.11.0。我知道过去每个驱动程序对GUID的处理方式不同,现在有了一个通用标准。出于向后兼容的原因,在C#驱动程序中默认不使用此功能。当前的建议似乎是在序列化程序上设置GuidRepresentation。全局或针对每个映射的Guid属性。
那很好,我面临的问题是对集合的查询不支持序列化设置,并且仅在使用不推荐使用的MongoDefaults设置时才能正常工作。使用正确的GuidRepresentation可以正确存储文档,但是查询似乎尝试匹配CSUUID而不是UUID,因此它永远不会与数据库中的文档匹配。
这是基本类地图:
public static void RegisterClassMaps()
{
BsonClassMap.RegisterClassMap<Widget>(cm =>
{
cm.MapIdProperty(w => w.Id)
.SetSerializer(new GuidSerializer(GuidRepresentation.Standard));
cm.MapProperty(w => w.ParentId)
.SetSerializer(new GuidSerializer(GuidRepresentation.Standard));
cm.MapProperty(w => w.Name);
}
}
这是一个匹配Guid和字符串的简单查询。以下方法将始终返回null,因为它使用CSUUID而不是UUID来构建查询。
private readonly IMongoCollection<Widget> _collection;
public async Task<Widget> FindByNameAsync(Guid parentId,string name)
{
var query = _collection.Find(w =>
w.ParentId == parentId &&
w.Name = name);
return await query.SingleOrDefaultAsync();
}
使用AsQueryable()而不是Find()具有相同的结果。两者都使用CSUUID而不是UUID构建查询。
我还尝试将全局GuidSerializer设置为使用GuidRepresentation.Standard,但是得到的结果相同。
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
如果我更改了不赞成使用的MongoDefaults属性的值,那么一切都会很好。
MongoDefaults.GuidRepresentation = GuidRepresantion.Standard;
我在构建查询方面缺少一些信息吗?我宁愿避免使用过时的设置。
解决方法
有同样的问题。
您需要配置GuidRepresentationMode,直到以后将其默认为V3
BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;
,
unique_edges = [('SLT2','SDP1'),('GCD7','ATG34'),('MTH1','MTH1'),('ADY2','ADY2')]
print([i for i in unique_edges if i[0] == i[1]])
BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
被标记为已弃用,因为在未来版本的驱动程序中,我们将删除对V2模式的支持,并且在那一刻,我们还将从BsonDefaults.GuidRepresentationMode
中删除GuidRepresentationMode
属性。 / p>