Skip to content

Instantly share code, notes, and snippets.

@christiannagel
Created August 30, 2018 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christiannagel/61a6c29366681288d3a19c829c369743 to your computer and use it in GitHub Desktop.
Save christiannagel/61a6c29366681288d3a19c829c369743 to your computer and use it in GitHub Desktop.
BooksService to create the Azure Cosmos DB database, and read and write entities
public class BooksService
{
private BooksContext _booksContext;
public BooksService(BooksContext booksContext) =>
_booksContext = booksContext ?? throw new ArgumentNullException(nameof(booksContext));
public async Task CreateTheDatabaseAsync()
{
var created = await _booksContext.Database.EnsureCreatedAsync();
if (created)
{
Console.WriteLine("database created");
}
else
{
Console.WriteLine("database already exists");
}
}
public async Task WriteBooksAsync()
{
_booksContext.Books.Add(new Book { BookId = Guid.NewGuid(), Title = "Professional C# 7 and .NET Core 2.0", Publisher = "Wrox Press" });
_booksContext.Books.Add(new Book { BookId = Guid.NewGuid(), Title = "Professional C# 6 and .NET Core 1.0", Publisher = "Wrox Press" });
_booksContext.Books.Add(new Book { BookId = Guid.NewGuid(), Title = "Enterprise Services with the .NET Framework", Publisher = "Addison Wesley" });
int changed = await _booksContext.SaveChangesAsync();
Console.WriteLine($"created {changed} records");
}
public void ReadBooks()
{
var books = _booksContext.Books.Where(b => b.Publisher == "Wrox Press");
foreach (var book in books)
{
Console.WriteLine($"{book.Title} {book.Publisher} {book.BookId}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment