您的位置:首页 > 数据库 > Mongodb

Using MongoDB with Web API and ASP.NET Core

2017-04-17 11:02 2041 查看

MongoDB is a NoSQL document-oriented database that allows you to define JSON based documents which are schema independent. The schema can be mapped with Tables in a Relational Database. A schema in MongoDB is called as collection, and a record in this schema is called as document

 Download an ASP.NET MVC CMS - Free Trial

In open source modern web applications, the use of a NoSQL database is gaining popularity due to its non-relational behavior. In this demo, we will create a Web API using ASP.NET Core which will perform CRUD Operations on a collection. The following diagram explains the implementation of the application.

The advantage of a Web API is that it can be used as HTTP services and can be subscribed by any client application ranging from Desktop to Mobiles. Using Web API as a medium, these client apps can easily interact with a NoSQL database like MongoDB.

Web API and MongoDB - The Implementation

We need MongoDB for creating collections and storing documents in it. MongoDB can be downloaded from this link. Install the database. Once the installation is over, the system drive will create a MongoDB folder in the following path

We also need to create a data folder where the data will be stored. On my machine I have created E:\MongoDbData\data

Open the Command prompt and navigate to the following folder

and run the command as shown in the following image

This will connect to MongoDB on port 27017.

Open another instance of the command prompt and navigate to the bin folder and run the following command

This will connect to the default test database. Run the following command on > (command prompt)

This will create a database of name EmployeeDB if it does not exist already, else it will be opened for transactions if the database already exists. In this database we can create transaction using the following command

The Schema for the Products collection can be defined using following command from the command prompt

Run the following command

The following result will be displayed

The schema will add _id property. This property will be an ObjectId which will be generated automatically.

Now since the database and collection is ready, we can create a Web API application. Please visit this link to read about creating Web API using MVC 6.

Creating the MongoDB Application

We will be using Visual Studio 2015 for creating this application. We need to install ASP.NET Core which can be downloaded from this link.

Step 1: Open Visual studio and create a new ASP.NET Web Application as shown in the following image

Name this application as MVC6_WEBAPI_MongoDB. Click on the OK button which will open the following window which shows ASP.NET Templates. Select Web API as shown in the following image

This will create a Web API project.

Step 2: Open the project.json file and in the dependencies section, add the following package dependency:

Save the project and the Mongo CSharp driver will be installed for the project.

Step 3: In the project add the Models folder, in this add a new class file of name Product.cs. Add the following code in this file

The class contains Id property of the type ObjectId. This property is mandatory so that the CLR object can be mapped with Collection in MongoDB. The class contains properties having the BsonElement attribute applied on it. This represent the mapped property with the MongoDB collection.

 

Step 3: Add the DataAccess.cs class file in the Models folder with the following code in it

The above code uses the following classes:

MongoServer - This represents an instance of the MongoDB Server.

MongoClient - This class is used to read the server instance for performing operations on the database. The constructor of this class is passed with the MongoDB Connection string as shown in the following box

MongoDatabase - This represents Mongo Database for performing operations. This class provides following methods

  • GetCollection<T>(collection)
  • · T is the CLR object to be collection.
  • · This returns MongoCollection.
  • Methods
  • FindAll() - Returns all documents in collection()
  • FindOne() - Returns a single document based on Mongo Query object generated based on _id.
  • Save() - Save a new document in collection.
  • Update() - Update a document.
  • Remove() - Remove a document.

The above code uses all these methods for performing CRUD operations.

Step 4: We will register the DataAccess class in the Dependency Injection feature provided by the ASP.NET Core. To do this open the Start.cs file and add the following line in ConfigureServices() method

Step 5: In the Controllers folder, add a new Web API Controller class of name ProductAPIController as shown in the following image

In this class add the following code

The above Web API class uses DataAccess class for performing CRUD operations. The Web API class contains GET, POST, PUT and DELETE methods for Http operations.

Step 5: Open the launchSettings.json in the Properties folder and add the following settings in it:

This provides launchUrl to run the application in IIS Express.

Run the application in browser and the following result will be displayed:

To Test this we will make use of Fiddler tool. Open the fiddler tool and enter the following URL in it

Click on Execute button and the following result will be displayed

To Post the data, enter the following details in Fiddler

Click on Execute button and the data will be posted. Run the following command from the Mongo Command prompt

The following result will be displayed

Conclusion: Using Mongo C# Driver we can easily connect to the popular MongoDB database and perform CRUD operations. Using ASP.NET WebAPI,  MongoDB data can be easily made available to various client apps for storing and reading data.

Download the source code of this article (Github)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: