2014-11-19 12 views
5

ho creato una classe C# in questo modo:System.FormatException' si è verificato in MongoDB.Bson.dll - XXX non è un 24 cifre stringa valida esadecimale

public class Employee 
    { 
     [BsonRepresentation(BsonType.ObjectId)] 
     public string Name { get; set; } 
     public int Age { get; set; } 
     public List<string> Address { get; set; } 
    } 

Quando cerco di salvare queste informazioni (usando MongoDB) in questo modo:

var e = new Employee(); 
    e.Address = new List<string>(); 
    e.Address.Add("Address 1"); 
    e.Address.Add("Address 2"); 

    e.Age = 333; 
    e.Name = "Some Name"; 

    context.Employees.Insert(e); 

sto ottenendo seguente errore:

An unhandled exception of type 'System.FormatException' occurred in MongoDB.Bson.dll 

Additional information: 'Some Name' is not a valid 24 digit hex string. 

Come posso rendere un campo stringa come ObjectID in MongoDB?

risposta

3

lettura dalla documentazione:

... In this case the serializer will convert the ObjectId to a string when reading data from the database and will convert the string back to an ObjectId when writing data to the database (the string value must be a valid ObjectId) ....

Si prega di rimuovere lo spazio bianco di stringa. Di tutto dovrebbe funzionare!

Per la prova wether avete un ObjectId valida, leggere il seguente SO-Post: MongoDB Node check if objectid is valid

EDIT: la risposta finale è stata: You have to change [BsonRepresentation(BsonType.ObjectId)] to [BsonId]

+0

Grazie per la risposta rapida. Ho rimosso lo spazio bianco e ho cambiato il codice in 'e.Name =" SomeName ";', ma sto ottenendo lo stesso errore. – SharpCoder

+1

@SharpCoder Cosa diminuisce quando si cambia '[BsonRepresentation (BsonType.ObjectId)]' a '[BsonId]'? – BendEg

+0

Sì. Questo aiuta !!! aggiungendo l'attributo '[BsonId]' invece di '[BsonRepresentation (BsonType.ObjectId)]' sulla proprietà 'userId' ha risolto il problema. Puoi aggiornare la tua risposta, questo aiuterà altri utenti in futuro !! Grazie !! – SharpCoder

1

Un tipo stringa ObjectId valida ha una stringa esadecimale 12bytes come '546c776b3e23f5f2ebdd3b03'.

Hai inserito [BsonRepresentation(BsonType.ObjectId)] per la tua proprietà Name. ciò significa che il driver C# converte una stringa in ObjectId e vise-versa automaticamente prima di qualsiasi operazione di serializzazione.

Rimuovere [BsonRepresentation(BsonType.ObjectId)] e

se si registra BsonSerializer.RegisterIdGenerator(typeof(string), new StringObjectIdGenerator()) a vostra app start up, e se si dispone di una proprietà denominata Id per la vostra entità, mongo stringa invece di ObjectId messo per i campi Id, ed è possibile utilizzare qualsiasi stringa come chiave per i campi Id.

Problemi correlati