我很难让我的模型将实体的Id属性表示为字符串,但它会自动生成,并在内部由MongoDb表示为本机ObjectId.

class Account
{
    public string Id { get; set; }
    ...
}

class AccountStore
{
    static AccountStore()
    {
        BsonClassMap.RegisterClassMap<Account>(cm =>
        {
            cm.AutoMap();
            cm.SetIgnoreExtraElements(true);

            // map Id property here
        });
    }

    public void Save(Account account)
    {
        _accounts.Save(account);
    }
}

对于上面代码中的第// map Id property here行,我try 了许多不同的方法来配置Id映射,但都没有成功.我try 过的方法,以及调用Save方法时引发的相关异常是:

// Exception: No IdGenerator found.
cm.IdMemberMap
  .SetRepresentation(BsonType.ObjectId);

// Exception: No IdGenerator found.
cm.IdMemberMap
  .SetRepresentation(BsonType.String);

// Exception: Unable to cast object of type 'MongoDB.Bson.ObjectId' to type 'System.String'.
cm.IdMemberMap
  .SetRepresentation(BsonType.ObjectId)
  .SetIdGenerator(ObjectIdGenerator.Instance);

// Exception: Unable to cast object of type 'MongoDB.Bson.ObjectId' to type 'System.String'.
cm.IdMemberMap
  .SetRepresentation(BsonType.String)
  .SetIdGenerator(ObjectIdGenerator.Instance);

// Exception: Unable to cast object of type 'MongoDB.Bson.ObjectId' to type 'System.String'.
cm.IdMemberMap
  .SetIdGenerator(ObjectIdGenerator.Instance);

我做错了什么?我以为这是id处理的标准用例?

推荐答案

这已经改变了,我正在使用最新的1.x驱动程序(Nuget package <package id="mongocsharpdriver" version="2.0.0" targetFramework="net45" />)并设置serialiser,而不是使用SetRepresentation.

public class RegistrationAttempt
{
    public string AttemptId { get; set; }
}

BsonClassMap.RegisterClassMap<RegistrationAttempt>(cm =>
{
    cm.AutoMap();
    cm.MapIdProperty(c => c.AttemptId)
        .SetIdGenerator(StringObjectIdGenerator.Instance)
        .SetSerializer(new StringSerializer(BsonType.ObjectId));
});

Mongodb相关问答推荐

MongoDB聚合:将文档列表转换为列表

MongoDB.ArrayFilters出错:在路径中找不到标识符';elem';的数组筛选器

MongoDB:如何获取多个$indexOfArray值?

为什么使用 Golang Mongo 驱动程序进行简单查询需要超过 2 秒?

Mongoose 聚合和多级组

在数据中只有月份和年份的 mongodb 中字符串的日期时间

MongoDB查询仅返回嵌入文档

如何在 mongodb 中设置整数的默认值?

你如何在 Kubernetes 上设置 Mongo 副本集?

Flask and Mongo

如何在 mongodb 本机驱动程序中对 find() 进行字段 Select ?

Mongo DB中的Upserting和Id问题

.NET 中的 Mongodb 单元测试

在 mongodb 中查找字段的所有非不同值

REACT 获取发布请求

当前的 URL 字符串解析器已弃用

Mongodb KeyFile 太开放权限

在 MongoDB 中插入或更新许多文档

有人在 Google App Engine 上try 过 MongoDB 吗?

MongoDB聚合框架的索引优化