MongoDB的C#:ID序列化的最佳模式 [英] MongoDB C#: ID Serialization best pattern
问题描述
我有一个类用户
,我需要在Web服务中与他们合作。
I have a class User
and I need to work with them in web services.
那么问题是如果我尝试序列编号
是 BsonObjectId
的类型,我看到
有一个空属性,这有一个空的财产,等等...
Then problem is that if I try to serialize Id
that is type of BsonObjectId
, I see
that have an empty property, that have an empty property, and so on ...
我写这篇文章的解决方法,才能,这是是一个好的解决方案?
I have write this workaround in order, it's is a good solution?
public partial class i_User
{
[BsonId(IdGenerator = typeof(BsonObjectIdGenerator))]
[NonSerialized]
public BsonObjectId _id;
public String Id
{
get
{
return this._id.ToString();
}
}
}
在这种方式,我可以保持 _id
为 BsonObjectId
,但我在属性发送在网上的字符串表示标识
。
In this way, I can keep _Id
as BsonObjectId
but I send an string representation over the web in the property Id
.
另一种方法是用 StringObjectIdGenerator
Another solution is to work with StringObjectIdGenerator
public partial class i_User
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public String id;
}
不过是看到MongoDB的将存储字符串
进入数据库,而不是的ObjectId
。
But is see that MongoDB will store a string
into database instead of ObjectId
.
什么是为了工作的最佳方法序列化环境如Web服务和/或客户端 - 服务器(Flash + C#)?
What is the best approach in order to work in a serialization environmental like web services and/or an client-server (Flash+C#)?
推荐答案
如果我理解正确的话,您要访问的编号
属性作为一个字符串,但有编号
另存为的ObjectId
在MongoDB中。这可以通过使用 BsonRepresentation
与 BsonId
来完成。
If I understand you correctly, you want to access the Id
property as a string, but have the Id
saved as an ObjectId
in MongoDB. This can be accomplished using BsonRepresentation
with BsonId
.
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
详细信息,可以发现的这里。
这篇关于MongoDB的C#:ID序列化的最佳模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!