Tuesday, December 10, 2019

MongoDB CRUD with Asp.Net Core Razor Pages - Simple Tutorial




This year I had the occasion to meet the MEAN stack, M coming from the Mongo DB NoSQL database. But, during my studies with Asp.Net Core, I am thinking about a database solution for future projects, outside the MS SQL realm. Might be suitable for side projects ? Who knows, I might give a try.

This is how I met Mongo DB, and produced this tutorial, with the plan that I might want to use MongoDB with .Net in the future.

Prerequisites:
1. Basic Asp.Net Core 2.2 Razor pages knowledge, check at least the first two tutorials mentioned here: https://mydev-journey.blogspot.com/2019/11/razor-pages-not-for-shaving.html
2. Check the introductory MongoDB API tutorial from Microsoft: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-2.2&tabs=visual-studio
3. My tutorial is based on point 2, just that it extends also to the front-end using Razor Pages, and then adds search function.
4. Please open an account on https://cloud.mongodb.com/ - it's free!
5. Download code from: https://drive.google.com/open?id=1FeihPX-qJz7b_zXraG32uHqoJLDTRcUr
6. Application LIVE online: http://mongotutorial.azurewebsites.net/ListBooks
7. Further study with C# from Mongo cloud provider: https://www.mongodb.com/blog/post/quick-start-csharp-and-mongodb--update-operation


A. After creating an account on the mongo cloud provider, create database on the Mongo Cloud, and a collection on the database, as below:

    "BooksCollectionName": "Books",
    "DatabaseName": "BookstoreDb"

Then, get the connection string from the Mongo Cloud, from connect application in below screen:
    "ConnectionString": "mongodb+srv://username:password@clusterxxx",


Connection string is inserted in the appsettings.json file.
B. You can replicate the tutorial on point 2 by following the material from Microsoft which I highly recommend, or simply take my zipped Repo from link.

Base class is the Book class, where I added an annotation for the Price to accept only currency values.
a. install Nuget Package: MongoDB.Driver
b. Book Class looks like:
insert
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
///
public class Book
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        [BsonElement("bookName")]
        public string BookName { get; set; }

        [BsonElement("price")]
        [DataType(DataType.Currency)]
        public decimal Price { get; set; }

        [BsonElement("category")]
        public string Category { get; set; }

        [BsonElement("author")]
        public string Author { get; set; }
    }



C. the main part here is the Services class which does the whole operation with the Mongo DB and collection, all CRUD operations. I added a search by title capability in my version.
insert: using MongoDB.Driver;
///
  public class BookService
    {
        private readonly IMongoCollection<Book> _books;

        public BookService(IBookstoreDatabaseSettings settings)
        {
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);

            _books = database.GetCollection<Book>(settings.BooksCollectionName);
        }

        public List<Book> Get() =>
            _books.Find(book => true).ToList();

        public List<Book> FindByTitle(string title) =>
            _books.Find(book => book.BookName.ToLower().Contains(title.ToLower())).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);
    }


D. My tutorial adds Razor pages to the project, which can display data, and do all the CRUD via separate pages. The Razor pages are scaffolded using a fake entity framework context, just to make the coding faster.

Basically, the CRUD Razor pages were scaffolded to Edit, Create, Delete or List all elements from the Mongo Table. Please follow the code to see the details.

E. In order to demonstrate the search capabilities of MongoDB, I added a form to search by book title,
The result of the application should look like below:

No comments:

Post a Comment