我正在将我的代码转移到新的 2.0 驱动程序,但遇到了 ObjectIds 问题。
之前我用 BsonId 和 BsonRepresentation 属性装饰了字符串 Id 属性。
现在我正在使用类映射
BsonClassMap.RegisterClassMap<Model>(cm =>
{
cm.MapIdMember(p => p.Id).SetIdGenerator(StringObjectIdGenerator.Instance);
cm.SetIgnoreExtraElements(true);
cm.AutoMap();
});
这个例子中的模型非常简单
public class Model
{
public string Id { get; set; }
public DateTime UpdatedTs { get; set; }
}
但是在插入之后,我将对象 ID 作为字符串返回,但它在服务器上也是一个字符串。
Image of MongoVue objectid is string
有什么我想念的吗?
谢谢 山姆
最佳答案
好的,感谢 Craig 对 mongodb 驱动程序团队的一些反馈,我得到的解决方案是:
cm.MapIdMember(p => p.Id)
.SetIdGenerator(StringObjectIdGenerator.Instance)
.SetSerializer(new StringSerializer(BsonType.ObjectId));
就像在装饰 Id 属性的属性时,您需要设置 Representation,在 v 2.0 中,您通过 SetSerializer 进行设置
HTH
关于c# - 使用 StringObjectIdGenerator 映射的 Id 在数据库中生成字符串 _id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29996654/