Connect MongoDB with Web API

2019-09-10 01:53发布

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.

1条回答
Fickle 薄情
2楼-- · 2019-09-10 02:29

The following code should work. Make sure you have the mongo database running in the background.

I've modified your code as follows

  1. I've added mongo connection URL when creating the MongoClient object so it will connect to local mongo Db.
  2. When saving the Books to the DB, instead of trying to save the array directly to the DB, the code is now looping over each item and saving it individually.

Here is the code

public IEnumerable<Book> Get()
{     
    var client = new MongoClient("mongodb://localhost:27017");
    var server = client.GetServer();
    var db = server.GetDatabase("BookStore");
    var collection = db.GetCollection<Book>("Book");
    Book[] books =
    {
         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" }
    };
    foreach (var book in books)
    {
        collection.Save(book);
    }
    return books;
}
查看更多
登录 后发表回答