【问题标题】:Mapped Id using StringObjectIdGenerator produces string _id in database使用 StringObjectIdGenerator 映射的 Id 在数据库中生成字符串 _id
【发布时间】:2015-05-01 23:39:15
【问题描述】:

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

我有什么遗漏吗?

谢谢 山姆

【问题讨论】:

  • 你能用 ObjectIdGenerator 代替 StringObjectIdGenerator 吗?
  • 我可以这样做,但这意味着将我的字符串 _id 映射属性更改为 ObjectId。我宁愿不做的事情。以前的驱动程序只是 [BsonRepresentation(BsonType.ObjectId)] public String Id { get; set; } - 不知道为什么它不起作用?

标签: c# mongodb


【解决方案1】:

好的,感谢 Craig 对 mongodb 驱动团队的一些反馈,我得到的解决方案是:

cm.MapIdMember(p => p.Id)
                .SetIdGenerator(StringObjectIdGenerator.Instance)
                .SetSerializer(new StringSerializer(BsonType.ObjectId));   

就像装饰 Id 属性的属性一样,您需要设置 Representation,在 v 2.0 中您通过 SetSerializer 执行此操作

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 2018-10-18
    • 2012-05-15
    • 2019-03-29
    • 1970-01-01
    • 2010-11-20
    相关资源
    最近更新 更多