c# - 使用 StringObjectIdGenerator 映射的 Id 在数据库中生成字符串 _id

标签 c# mongodb

我正在将我的代码转移到新的 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/

相关文章:

javascript - 如何在mongodb中查询数组

python - 如何从发布的 base64 编码图像创建 MongoDB/mongoengine ImageField?

javascript - 在 MEAN CRUD 应用程序中确认删除后无法读取未定义的属性 '_id'?

c# - 随机数概率

c# - 使用 UpdateTimestampsCache 进行优化

C# : Printing variables and text in a textbox

javascript - Mongoose - 使用 populate 方法后如何处理结果?

mongodb - 如何删除 WiredTigerStat.XX.XX 文件?

c# - 从 Azure Function HttpTrigger 返回错误详细信息

c# - 使用 autofac 注册多个 dbcontext,其中构建器不可用于注册后解析类