Se lo stai facendo all'interno di un async metodo, quindi la risposta di Brduca funzionerà (ed è preferibile), altrimenti puoi chiamare Wait()
nel Task restituito da InsertOneAsync chiama per assicurarti che la tua applicazione rimanga abbastanza a lungo per vedere l'eccezione della chiave duplicata:
commandsCollection.InsertOneAsync(doc).Wait();
Se l'inserimento non riesce a causa di una chiave duplicata, Wait() genererà un AggregateException che contiene una MongoWriteException che contiene i dettagli della chiave duplicata.
try
{
commandsCollection.InsertOneAsync(doc).Wait();
}
catch(AggregateException aggEx)
{
aggEx.Handle(x =>
{
var mwx = x as MongoWriteException;
if (mwx != null && mwx.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
// mwx.WriteError.Message contains the duplicate key error message
return true;
}
return false;
});
}
Allo stesso modo, se stai usando await , che genererà un AggregateException anche.
Per evitare la complessità aggiuntiva di AggregateException avvolgendo l'eccezione mongo, puoi chiamare GetAwaiter().GetResult() invece di Wait() :
try
{
commandsCollection.InsertOneAsync(doc).GetAwaiter().GetResult();
}
catch(MongoWriteException mwx)
{
if (mwx.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
// mwx.WriteError.Message contains the duplicate key error message
}
}