我正在尝试在Visual Studio 2013中将MongoDB与Web API连接。我想要做的就是使用C#创建一个简单的数据库。我的所有代码都在ValuesControllers.cs文件中。我创建了一个简单的Model类 -
public class Book
{
[BsonId]
public int Id { get; set; }
public string Title { get; set; }
}
并修改了Get方法
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;
}
它返回值但不创建数据库。我在控制台应用程序中尝试了这个并且它可行 我想用一个简单的例子来连接MongoDB。
答案 0 :(得分:0)
以下代码应该有效。确保在后台运行mongo数据库。
我修改了你的代码如下
这是代码
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;
}