Creating Documents in CosmosDB with .NET
Syntax
using Microsoft.Azure.Cosmos;
var container = cosmosClient.GetContainer("databaseId", "containerId");
var item = new YourModelClass
{
/*property values*/
};
await container.CreateItemAsync(item, new PartitionKey(item.Id));
Example
using Microsoft.Azure.Cosmos;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;
public class ToDoItem
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "taskName")]
public string TaskName { get; set; }
[JsonProperty(PropertyName = "isComplete")]
public bool IsComplete { get; set; }
[JsonProperty(PropertyName = "assignedTo")]
public string AssignedTo { get; set; }
}
public async Task CreateDocumentAsync()
{
var container = cosmosClient.GetContainer("TasksDB", "ToDoItems");
var item = new ToDoItem
{
Id = "1",
TaskName = "Learn CosmosDB",
IsComplete = false,
AssignedTo = "John Doe"
};
await container.CreateItemAsync(item, new PartitionKey(item.Id));
}
Output
After running the CreateDocumentAsync()
method, a new document with TaskName "Learn CosmosDB" will be created in the "TasksDB" database and "ToDoItems" container.
Explanation
To create a new document in CosmosDB using .NET, you need to first initialize a CosmosClient instance. Using this client, you can get a reference to the container where you want to create the document. Once you have the container reference, you can create a new instance of your model class and set the property values.
Finally, you can call the CreateItemAsync()
method on the container reference passing the model object and the partition key value. CosmosDB will automatically assign a partition key based on the value provided and create a new document in the container.
Use
Creating documents is a fundamental operation in CosmosDB. You can create new documents to store data for various entities in your application. This data can be retrieved later using various querying options.
Important Points
- The model class used to represent a CosmosDB document must have a public property named "Id" of type string.
- The
CreateItemAsync()
method will throw a CosmosException if the document already exists in the container. - The partition key value should be unique for each document to take advantage of the horizontal partitioning in CosmosDB.
Summary
In this tutorial, you learned how to create a new document in CosmosDB using .NET SDK. You learned about the syntax, example, output, explanation, use, important points, and summary of creating documents in CosmosDB.