如何告诉MongoDB C#驱动程序以字符串格式存储所有Guid? [英] How can I tell the MongoDB C# driver to store all Guids in string format?

查看:241
本文介绍了如何告诉MongoDB C#驱动程序以字符串格式存储所有Guid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将[BsonRepresentation(BsonType.String)]属性应用于域模型中的所有Guid属性,以使这些属性以字符串格式序列化.除了做起来很累之外,有时也无法解决问题,例如使用自定义的Wrapper<T>类:

I'm currently applying the [BsonRepresentation(BsonType.String)] attribute to all Guid properties in my domain models to have those properties serialized in string format. Besides being tiresome to do, that doesn't work out sometimes, e.g. with custom Wrapper<T> classes:

public class Wrapper<T>
{
    public T Value { get; set; }

    // Further properties / business logic ...
}

TGuid时,Value属性将存储为类型为UuidLegacy的二进制数据(没有使用上述属性修饰的类型为Guid的任何属性).但是,我希望所有Guid(包括Wrapper<Guid>.Value)在数据库中都表示为字符串.

When T is Guid, the Value property will be stored as binary data of type UuidLegacy (as will any property of type Guid that's not decorated with the above attribute). However, I'd like all Guids, including Wrapper<Guid>.Value, to be represented as a string in the database.

有什么办法告诉MongoDB C#驱动程序以字符串格式存储所有Guid吗?

Is there any way to tell the MongoDB C# driver to store all Guids in string format?

推荐答案

可以使用约定来实现

类似的东西:

var myConventions = new ConventionProfile();
myConventions.SetSerializationOptionsConvention(
    new TypeRepresentationSerializationOptionsConvention(typeof (Guid), BsonType.String));

BsonClassMap.RegisterConventions(myConventions, t => t == typeof (MyClass));

这应该在您的应用启动时进行.

This should go somewhere in your app startup.

您可以在此处阅读有关约定的更多信息: http://www.mongodb .org/display/DOCS/CSharp + Driver + Serialization + Tutorial#CSharpDriverSerializationTutorial-Conventions

You can read more about conventions here: http://www.mongodb.org/display/DOCS/CSharp+Driver+Serialization+Tutorial#CSharpDriverSerializationTutorial-Conventions

这篇关于如何告诉MongoDB C#驱动程序以字符串格式存储所有Guid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆