Mam problem z tym, aby mój model reprezentował właściwość obiektu w postaci Id
jako ciąg, ale automatycznie wygenerował i reprezentował wewnętrznie MongoDb jako natywny ObjectId
.Sterownik MongoDB C# - jak przechowywać _id jako ObjectId, ale odwzorować na właściwość Id łańcucha?
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);
}
}
Dla linii // map Id property here
w powyższym kodzie, próbowałem wiele różnych sposobów konfiguracji mapowania identyfikatora i żaden z nich nie pracował. Sposoby próbowałem i związane z nim wyjątki, które są rzucane, gdy nazywam Save
metoda, są:
// 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);
Co robię źle? Myślałem, że to był standardowy przypadek użycia do obsługi identyfikatora?
Możliwy duplikat [Jak stosować atrybut BsonRepresentation umownie przy użyciu MongoDB] (https://stackoverflow.com/questions/45043266/how-to- apply-bsonrepresent ation-attribute-by-convention-when-using-mongodb) – dnickless