问题描述
我无法让我的模型将实体的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属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!