Skip to content

Instantly share code, notes, and snippets.

@tuannguyenssu
Created September 26, 2019 14:53
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 tuannguyenssu/50c29ac03d4bfaec4f35c0fddd297ee3 to your computer and use it in GitHub Desktop.
Save tuannguyenssu/50c29ac03d4bfaec4f35c0fddd297ee3 to your computer and use it in GitHub Desktop.
using MongoDBTest.Models;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Linq;
namespace MongoDBTest.Services
{
public class BookService
{
private readonly IMongoCollection<Book> _books;
private const string ConnectionString = "mongodb://localhost:27017";
private const string DatabaseName = "BookstoreDb";
private const string BooksCollectionName = "Books";
public BookService()
{
var client = new MongoClient(ConnectionString);
var database = client.GetDatabase(DatabaseName);
_books = database.GetCollection<Book>(BooksCollectionName);
}
public List<Book> Get() =>
_books.Find(book => true).ToList();
public Book Get(string id) =>
_books.Find<Book>(book => book.Id == id).FirstOrDefault();
public Book Create(Book book)
{
_books.InsertOne(book);
return book;
}
public void Update(string id, Book bookIn) =>
_books.ReplaceOne(book => book.Id == id, bookIn);
public void Remove(Book bookIn) =>
_books.DeleteOne(book => book.Id == bookIn.Id);
public void Remove(string id) =>
_books.DeleteOne(book => book.Id == id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment