Friday, April 17, 2020

Writing Data Access Layer in C# for MongoDB

As discussed from our previous post, MongoDB is pretty good if we can work it in int's unique way. So, to do all of the work, we need to have a propert DB layer. Let's first look at how we can connect and then do a sample select.

 var client = new MongoClient("mongodb://localhost:27017");  
 mongoDatabase = client.GetDatabase("TemplateManager");  
 public List<T> Select<T>(string TableName, string SelectColumnName, BsonValue WhereValue)  
     {  
       var collection = mongoDatabase.GetCollection<T>(TableName);  
       var filter = Builders<T>.Filter.Eq(SelectColumnName, WhereValue);  
       return collection.Find(filter).ToList();  
     }    

Using above code, you can connect to the locally installed DB server get a list of records which can be converted into a list of entity.

Lets see how this is used.

 List<Person> personList = new bllPerson().Select();  

The Person is an entity which we use in the collection. The bllPerson is a class that handles DB calls. So it gets all the people saved under Person collection in the Database.

Try it and next time lets talk about Updated and Delete method.

Happy coding.

Sunday, April 5, 2020

Using MongoDB for your .Net applications - Data Access (Layer)

Hopefully you might have worked on MongoDB or probably not. Anyway, MongoDB can be downloaded https://www.mongodb.com/download-center/community here. It's the community version and free version. Install and run the server. It runs on localhost:27017.

If you want to know more about what is MongoDB, visit here https://www.mongodb.com/what-is-mongodb


When you download the server and install, you can easily do all the CRUD operations. for that you need to install the MongoDB nuget package. Those have the necessary dlls to perform database actions. following are the packages you need to install.


Once you have it, you can reference the namespaces.



So, you now you are ready to write your own codes to deal with MongoDB. For example, you can think of the following code.























This is how you can get this to use in your front end.





try to understand the basics here. documentation of MongoDB is here (https://developer.mongodb.com/learn?languages=C%23)

Next time, lets see how we can write our own Data Access Layer.

Until that, happy coding.