MongoDB (server v 2.6.7) with C# driver 2.0: How to get the result from InsertOneAsync

后端 未结 3 501
囚心锁ツ
囚心锁ツ 2020-12-16 02:23

I am testing MongoDB (server v 2.6.7) with the C# driver 2.0.

When I am using the insert function InsertOneAsync for a document with an _id

3条回答
  •  余生分开走
    2020-12-16 02:50

    If you're doing this within an async method, then Brduca's answer will work (and is preferrable), otherwise you can call Wait() on the Task returned from the InsertOneAsync call to ensure your application stays around long enough to see the duplicate key exception:

    commandsCollection.InsertOneAsync(doc).Wait();
    

    If the insert fails because of a duplicate key, the Wait() will throw an AggregateException that contains a MongoWriteException that contains the duplicate key details.

    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;
        });
    }
    

    Similarly, if you're using await, that will throw an AggregateException as well.

    To avoid the added complexity of the AggregateException wrapping the mongo exception, you can call GetAwaiter().GetResult() instead of 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
        }
    }
    

提交回复
热议问题