1

I think I am on the right path, but my C# code is not creating document in Azure CosmosDB. Below is my documentdb code:

using (var client = new DocumentClient(new Uri(endpoint), authkey))
{
    Database database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'db'").AsEnumerable().First();
    var query = new SqlQuerySpec
    {
        QueryText = "SELECT * FROM c WHERE c.id = @id",
        Parameters = new Microsoft.Azure.Documents.SqlParameterCollection { new Microsoft.Azure.Documents.SqlParameter { Name = "@id", Value = collectionId }
    }
};

DocumentCollection collection = client.CreateDocumentCollectionQuery(database.SelfLink,query).AsEnumerable().First();

dynamic document1Definition = new
{
    name = "Admin",
    address = 1,
};

var result = client.CreateDocumentAsync(collection.SelfLink, document1Definition);

}

Also want to point out, currently there are no columns named as "name" and "address" in my collection. So according to my knowledge they are suppose to be created dynamically. Please let me know what wrong are you doing?

Jerry Liu
  • 17,282
  • 4
  • 40
  • 61
Zhrez Pain
  • 327
  • 1
  • 2
  • 10
  • On a side not, it might worth talking a look at [Cosmonaut](https://github.com/Elfocrash/Cosmonaut). It supports all the C# SDK functionality in a more tidied up way. You could simply do a `await store.AddAsync(document1Definition)` and it would work. Disclaimer, I created this library. – Nick Chapsas Jul 31 '18 at 08:12
  • I just ran the code (I only added a `.GetAwaiter().GetResult()` at the end of the `CreateDocumentAsync` (which is not what you should do, you should use await but anyway)) from the post locally and it works like a charm btw. Could it be that you're using a Read-Only key? – Nick Chapsas Jul 31 '18 at 08:19

1 Answers1

3

See last statement, you are using c# Async method without await.

Use await client.CreateDocumentAsync(collection.SelfLink, document1Definition); or your code will exit before document creation is finished.

Note that your method should change to public async Task methodname(), you will see related tip shown by VS.

Some references for you

Jerry Liu
  • 17,282
  • 4
  • 40
  • 61
  • If I add await, the web page keeps on loading. The execution doesn't complete nor throws any error. – Zhrez Pain Jul 31 '18 at 05:48
  • @ZhrezPain Could you describe how you call this method(or show some related context) in your web app? Your code works in console application. – Jerry Liu Jul 31 '18 at 05:53