Skip to content

Instantly share code, notes, and snippets.

@skarllot
Created April 2, 2023 00:40
Show Gist options
  • Save skarllot/dd2907f49d41c4619156135937cf092b to your computer and use it in GitHub Desktop.
Save skarllot/dd2907f49d41c4619156135937cf092b to your computer and use it in GitHub Desktop.
Using Azure Cosmos DB and Entity Framework Core
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
namespace CosmosCodeFirstDemo
{
class Program
{
static async Task Main(string[] args)
{
// Read the configuration from the appsettings.json file
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
// Create a new service collection and add the configuration and logging
var services = new ServiceCollection()
.AddSingleton(configuration)
.AddLogging(builder => builder.AddConsole())
.BuildServiceProvider();
// Create a new instance of the CosmosDbContext
var dbContext = services.GetService<CosmosDbContext>();
// Create the Cosmos DB database and container if they don't already exist
await dbContext.Database.EnsureCreatedAsync();
// Add a new person to the database
await dbContext.People.AddAsync(new Person { Id = Guid.NewGuid(), FirstName = "John", LastName = "Doe", Age = 35 });
await dbContext.SaveChangesAsync();
// Retrieve all people from the database and print their names and ages
var people = await dbContext.People.ToListAsync();
foreach (var person in people)
{
Console.WriteLine($"{person.FirstName} {person.LastName}, age {person.Age}");
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
public class Person
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
public class CosmosDbContext : DbContext
{
private readonly IConfiguration configuration;
public CosmosDbContext(IConfiguration configuration)
{
this.configuration = configuration;
}
public DbSet<Person> People { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Get the Cosmos DB configuration values from the appsettings.json file
var endpoint = configuration["CosmosDb:Endpoint"];
var key = configuration["CosmosDb:Key"];
var databaseName = configuration["CosmosDb:DatabaseName"];
var containerName = configuration["CosmosDb:ContainerName"];
// Configure the DbContext to use Cosmos DB
optionsBuilder.UseCosmos(endpoint, key, databaseName, options =>
{
// Set the container throughput to 400 RU/s
options.ConnectionMode(ConnectionMode.Gateway);
options.WebProxy(new System.Net.WebProxy());
options.ContainerThroughput(400);
options.AllowBulkExecution(true);
options.ApplicationName("CosmosCodeFirstDemo");
options.ApplicationRegion(Regions.WestUS2);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment