Problem

How to use Azure NoSQL database in ASP.NET Core.

Solution

Create a class library and add NuGet package Microsoft.Azure.DocumentDB.Core.

Add a class to encapsulate settings,

  1. public class AzureNoSqlSettings
  2. {
  3. public AzureNoSqlSettings(string endpoint, string authKey,
  4. string databaseId, string collectionId)
  5. {
  6. if (string.IsNullOrEmpty(endpoint))
  7. throw new ArgumentNullException("Endpoint");
  8. if (string.IsNullOrEmpty(authKey))
  9. throw new ArgumentNullException("AuthKey");
  10. if (string.IsNullOrEmpty(databaseId))
  11. throw new ArgumentNullException("DatabaseId");
  12. if (string.IsNullOrEmpty(collectionId))
  13. throw new ArgumentNullException("CollectionId");
  14. this.Endpoint = endpoint;
  15. this.AuthKey = authKey;
  16. this.DatabaseId = databaseId;
  17. this.CollectionId = collectionId;
  18. }
  19. public string Endpoint { get; }
  20. public string AuthKey { get; }
  21. public string DatabaseId { get; }
  22. public string CollectionId { get; }
  23. }

Add a class for repository, which will work with a generic type. Add a constructor and private methods to initialize the Azure client,

  1. public AzureNoSqlRepository(AzureNoSqlSettings settings)
  2. {
  3. this.settings = settings ?? throw new ArgumentNullException("Settings");
  4. Init();
  5. }
  6. private AzureNoSqlSettings settings;
  7. private DocumentClient client;
  8. private void Init()
  9. {
  10. client = new DocumentClient(
  11. new Uri(this.settings.Endpoint), this.settings.AuthKey);
  12. CreateDatabaseIfNotExistsAsync().Wait();
  13. CreateCollectionIfNotExistsAsync().Wait();
  14. }
  15. private async Task CreateDatabaseIfNotExistsAsync()
  16. {
  17. await client.ReadDatabaseAsync(
  18. UriFactory.CreateDatabaseUri(this.settings.DatabaseId));
  19. }
  20. private async Task CreateCollectionIfNotExistsAsync()
  21. {
  22. await client.ReadDocumentCollectionAsync(
  23. UriFactory.CreateDocumentCollectionUri(
  24. this.settings.DatabaseId, this.settings.CollectionId));
  25. }

Add methods to get one or more items,

  1. private Uri GetCollectionUri()
  2. {
  3. return UriFactory.CreateDocumentCollectionUri(
  4. this.settings.DatabaseId, this.settings.CollectionId);
  5. }
  6. private Uri GetDocumentUri(string documentId)
  7. {
  8. return UriFactory.CreateDocumentUri(
  9. this.settings.DatabaseId, this.settings.CollectionId, documentId);
  10. }

Now add public methods for the repository,

  1. public async Task<List<T>> GetList()
  2. {
  3. var query = this.client
  4. .CreateDocumentQuery<T>(GetCollectionUri())
  5. .AsDocumentQuery();
  6. var results = new List<T>();
  7. while (query.HasMoreResults)
  8. {
  9. results.AddRange(await query.ExecuteNextAsync<T>());
  10. }
  11. return results;
  12. }
  13. public async Task<T> GetItem(string id)
  14. {
  15. Document document = await this.client.ReadDocumentAsync(
  16. GetDocumentUri(id));
  17. return (T)(dynamic)document;
  18. }
  19. public async Task<Document> Insert(T item)
  20. {
  21. return await this.client.CreateDocumentAsync(GetCollectionUri(), item);
  22. }
  23. public async Task<Document> Update(string id, T item)
  24. {
  25. return await this.client.ReplaceDocumentAsync(GetDocumentUri(id), item);
  26. }
  27. public async Task<Document> InsertOrUpdate(T item)
  28. {
  29. return await this.client.UpsertDocumentAsync(GetCollectionUri(), item);
  30. }
  31. public async Task Delete(string id)
  32. {
  33. await this.client.DeleteDocumentAsync(GetDocumentUri(id));
  34. }

Inject and use repository,

  1. public class MovieService : IMovieService
  2. {
  3. private readonly IAzureNoSqlRepository<Movie> repository;
  4. public MovieService(IAzureNoSqlRepository<Movie> repository)
  5. {
  6. this.repository = repository;
  7. }

In ASP.NET Core Web Application, configure services,

  1. public void ConfigureServices(
  2. IServiceCollection services)
  3. {
  4. services.AddScoped<IAzureNoSqlRepository<Movie>>(factory =>
  5. {
  6. return new AzureNoSqlRepository<Movie>(
  7. new AzureNoSqlSettings(
  8. endpoint: Configuration["NoSql_Endpoint"],
  9. authKey: Configuration["NoSql_AuthKey"],
  10. databaseId: Configuration["NoSql_Database"],
  11. collectionId: Configuration["NoSql_Collection"]));
  12. });
  13. services.AddScoped<IMovieService, MovieService>();
  14. services.AddMvc();
  15. }

Discussion

The sample code will require you to setup Azure account, NoSQL database and collection. Instructions for these can be found here.

Source Code