I am trying to connect MongoDB with Web API in Visual Studio 2013. All I want to do is create a simple database with C#. All of my code is in ValuesControllers.cs file. I created a simple Model class -
public class Book
{
[BsonId]
public int Id { get; set; }
public string Title { get; set; }
}
and modified the Get method
public IEnumerable<Book> Get()
{
MongoClient client = new MongoClient();
var server = client.GetServer();
var db = server.GetDatabase("BookStore");
var collection = db.GetCollection<Book>("Book");
Book[] books = new Book[]
{
new Book {Id = 1, Title="Book Name 1" },
new Book {Id = 2, Title="Book Name 2" },
new Book {Id = 3, Title="Book Name 3" },
new Book {Id = 4, Title="Book Name 4" }
};
collection.Save(books);
return books;
}
It returns values but doesn't create database. I tried this in console application and it works. I want to make a simple example to connect MongoDB.
The following code should work. Make sure you have the mongo database running in the background.
I've modified your code as follows
Here is the code