MongoDB C#驱动程序-如何将_id存储为ObjectId但映射到字符串Id属性? [英] MongoDB C# Driver - how to store _id as ObjectId but map to string Id property?

查看:230
本文介绍了MongoDB C#驱动程序-如何将_id存储为ObjectId但映射到字符串Id属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having trouble getting my model to represent an entity's Id property as a string but have it auto-generated and represented internally by MongoDb as a native 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,我尝试了多种不同的方法来配置ID映射,但没有一种有效.我尝试过的方式以及调用Save方法时引发的相关异常是:

For the line // map Id property here in the above code, I've tried numerous different ways of configuring the Id mapping and none have worked. The ways I have tried, and the associated exceptions that are thrown when I call the Save method, are:

// 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处理的标准用例?

What am I doing wrong? I thought this was a standard use case for id handling?

推荐答案

这已更改,我使用的是最新的1.x驱动程序(Nuget包<package id="mongocsharpdriver" version="2.0.0" targetFramework="net45" />),而不是使用SetRepresentation来设置序列化程序.

This has changed, I'm using the latest 1.x driver (Nuget package <package id="mongocsharpdriver" version="2.0.0" targetFramework="net45" />) and instead of using SetRepresentation you set the serialiser.

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 C#驱动程序-如何将_id存储为ObjectId但映射到字符串Id属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆