MongoDB C#:ID序列化最佳模式
我有一个类User
,我需要在Web服务中使用它们。
然后问题是,如果我尝试序列化类型为BsonObjectId
Id
,我看到它有一个空属性,有一个空属性,依此类推……
我按顺序编写了这个解决方法,这是一个很好的解决方案吗?
public partial class i_User { [BsonId(IdGenerator = typeof(BsonObjectIdGenerator))] [NonSerialized] public BsonObjectId _id; public String Id { get { return this._id.ToString(); } } }
通过这种方式,我可以将_Id
保持为BsonObjectId
但是我在属性Id
通过Web发送字符串表示。
另一种解决方案是使用StringObjectIdGenerator
public partial class i_User { [BsonId(IdGenerator = typeof(StringObjectIdGenerator))] public String id; }
但是看到MongoDB会将string
存储到数据库而不是ObjectId
。
在Web服务和/或客户端服务器(Flash + C#)等序列化环境中工作的最佳方法是什么?
如果我理解正确,您希望以字符串forms访问Id
属性,但将Id
保存为MongoDB中的ObjectId
。 这可以使用BsonRepresentation
的BsonId
来完成。
[BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; }
细节可以在这里找到。
如果你想用类映射来做 – 这是这样做的方法:
BsonClassMap.RegisterClassMap(cm => { cm.AutoMap(); cm.SetIdMember(cm.GetMemberMap(x => x.Id) .SetIdGenerator(StringObjectIdGenerator.Instance)); });
还有一种使用约定的更通用的方法。 此方法允许您在一个位置设置所有模型的规则。
第一。 为ID生成器添加约定
public class IdGeneratorConvention : ConventionBase, IPostProcessingConvention { public void PostProcess(BsonClassMap classMap) { var idMemberMap = classMap.IdMemberMap; if (idMemberMap == null || idMemberMap.IdGenerator != null) { return; } idMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance); } }
第二。 注册我们的会议。 必须在第一次查询之前调用Register
方法。
var conventionPack = new ConventionPack { new IdGeneratorConvention() }; ConventionRegistry.Register("Pack", conventionPack, x => true);