我很难让我的模型将实体的Id
属性表示为字符串,但无法自动生成并由MongoDb内部将其表示为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
方法时引发的相关异常是:
// 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 id="mongocsharpdriver" version="2.0.0" targetFramework="net45" />
),而不是使用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));
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句