Mongo db C# 序列化
我正在尝试使用 Mongo Db 的 10gen C# 驱动程序编写以下代码。我在这里想要实现的是编写一个简单的适配器,以便无缝缓存 C# 对象。
RegisterClassMap() 无法识别类契约中的 CacheId 字段。我在 MapIdField api 上找不到足够的文档。
有人可以帮忙吗?提前致谢 !!
public interface ICacheable
{
byte[] CacheId { get; }
}
public class Contract : ICacheable
{
public byte[] CacheId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class MongoCacheStore
{
private void RegisterClass<T>() where T : class, ICacheable
{
if (!BsonClassMap.IsClassMapRegistered(typeof(T)))
{
BsonClassMap.RegisterClassMap<T>();
BsonClassMap.RegisterClassMap<T>(cm =>
{
cm.AutoMap();
**cm.MapIdField("CacheId");**
});
}
}
}
I'm trying to write the following code using 10gen C# drivers for Mongo Db. What I'm trying to achieve here is that write a simple adapter so as to seamlessly cache C# objects.
The RegisterClassMap() is not able to recognize CacheId field from the class contract. I couldn't find enough documentation on MapIdField api.
Can somebody please help ? Thanks in advance !!
public interface ICacheable
{
byte[] CacheId { get; }
}
public class Contract : ICacheable
{
public byte[] CacheId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class MongoCacheStore
{
private void RegisterClass<T>() where T : class, ICacheable
{
if (!BsonClassMap.IsClassMapRegistered(typeof(T)))
{
BsonClassMap.RegisterClassMap<T>();
BsonClassMap.RegisterClassMap<T>(cm =>
{
cm.AutoMap();
**cm.MapIdField("CacheId");**
});
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下内容对我有用:
您必须使用 MapIdProperty 而不是 MapIdField,因为 CacheId 是一个属性。
您的意思是界面中没有设置访问器吗?
另外,如果您安排 RegisterClass 仅调用一次,而不是每次都测试 IsClassMapRegistered,那就更好了。其一,我认为它不是书面的线程安全的(两个线程都可能从调用 IsClassMapRegistered 中得到错误返回,并且其中一个线程在调用 RegisterClassMap 时会失败)。
The following worked for me:
You have to use MapIdProperty instead of MapIdField because CacheId is a property.
Did you mean to not have a set accessor in the interface?
Also, it is much better if you arrange to have RegisterClass only called once rather then testing for IsClassMapRegistered every time. For one, I don't think it is thread safe as written (two threads could both get false back from calling IsClassMapRegistered and one of them is going to fail when calling RegisterClassMap).