MongoDB C#:ID序列化最佳模式
我有一个classMongoDB C#:ID序列化最佳模式,c#,mongodb,C#,Mongodb,我有一个classUser,我需要在web服务中与他们一起工作 然后问题是,如果我尝试序列化Id,这是BsonObjectId的类型,我会看到 有空属性的,有空属性的,等等 我已按顺序编写了此解决方案,这是一个好的解决方案吗 public partial class i_User { [BsonId(IdGenerator = typeof(BsonObjectIdGenerator))] [NonSerialized] public BsonObjectId _id;
User
,我需要在web服务中与他们一起工作
然后问题是,如果我尝试序列化Id
,这是BsonObjectId
的类型,我会看到
有空属性的,有空属性的,等等
我已按顺序编写了此解决方案,这是一个好的解决方案吗
public partial class i_User
{
[BsonId(IdGenerator = typeof(BsonObjectIdGenerator))]
[NonSerialized]
public BsonObjectId _id;
public String Id
{
get
{
return this._id.ToString();
}
}
}
通过这种方式,我可以将\u Id
保留为BsonObjectId
,但我可以通过web在属性Id
中发送字符串表示
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
另一个解决方案是使用StringObjectiveGenerator
public partial class i_User
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public String id;
}
但是可以看到MongoDB将把字符串
存储到数据库中,而不是ObjectId
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
在web服务和/或客户端服务器(Flash+C#)等序列化环境中工作的最佳方法是什么?如果我理解正确,您希望以字符串形式访问
Id
属性,但将Id
保存为MongoDB中的ObjectId
。这可以通过使用BsonRepresentation
和BsonId
来实现
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
可以找到详细信息。如果您想使用类映射执行此操作,请使用以下方法:
BsonClassMap.RegisterClassMap<i_User>(cm =>
{
cm.AutoMap();
cm.SetIdMember(cm.GetMemberMap(x => x.Id)
.SetIdGenerator(StringObjectIdGenerator.Instance));
});
BsonClassMap.RegisterClassMap(cm=>
{
cm.AutoMap();
cm.SetIdMember(cm.GetMemberMap(x=>x.Id)
.SetIdGenerator(StringObjectiveGenerator.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);
}
}
第二。登记我们的公约<在第一次查询之前,必须调用code>Register方法
var conventionPack = new ConventionPack { new IdGeneratorConvention() };
ConventionRegistry.Register("Pack", conventionPack, x => true);
花了2个小时处理不会序列化原始ObjectId的webapi响应。这为我节省了大概2个多小时的时间。几个小时后,我终于找到了这个。万分感谢!很高兴这个答案是有帮助的,只是看起来对作者没有帮助。这很有效,但并不是我所希望的。我的愿望是保持我的POCO类不依赖于Mongo。在BsonClassMap中,将其移动到存储库层,是否没有办法实现这一点?非常感谢您给出这个答案,我今天感到非常沮丧。很抱歉,这对你也没有帮助。这是一个很好的方法,让POCO保持干净,这是我最关心的。但它实际上会在Mongo中将Id存储为字符串。理想情况是在数据库中使用ObjectId表示,在POCO中使用字符串表示。这可能吗?我不知道,但我想你可以修改C#驱动程序。使用ObjectId的目的是它只需要12个字节,并且具有内置时间戳。为什么不在您的域实体中使用ObjectId?谢谢您的快速回答。我通常希望我的域层独立于存储层技术。但我想一切都是一种权衡。