使用MongoRepository的多个数据库

时间:2013-10-18 16:19:29

标签: c# mongodb mongorepository

我正在使用Mongo Repository与mongo数据库通信。

这是我的连接字符串。

<connectionStrings>
   <!-- See http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-Connectionstrings for more info -->
   <add name="MongoServerSettings" connectionString="mongodb://myDomain:27017/myDatabase1" />
</connectionStrings>

然后我就这样使用它:

using System;
using System.Linq;
using MongoRepository;

class Program
{
    static MongoRepository<Customer> customerrepo = new MongoRepository<Customer>();

    static void Main(string[] args)
    {

        //Add customers
        var john = new Customer() { FirstName = "John", LastName = "Doe" };
        var jane = new Customer() { FirstName = "Jane", LastName = "Doe" };
        var jerry = new Customer() { FirstName = "Jerry", LastName = "Maguire" };
        customerrepo.Add(new[] { john, jane, jerry });
    }
}

这很好用。但是我如何配置它以便它可以与2个或更多数据库通信。

感谢。

1 个答案:

答案 0 :(得分:2)

MongoRepository<T>类有一个构造函数,它将连接字符串或mongo url作为参数。

如果您希望myDatabase2上的存储库只是使用正确的连接字符串实例化MongoRepository。例如:

var customerRepoOnDb2 = new MongoRepository<Customer>("mongodb://myServer/myDatabase2");

您可以将连接字符串添加到配置中:

<connectionStrings>
  <add name="MongoServerSettings" connectionString="mongodb://myDomain:27017/myDatabase1" />
  <add name="MongoServerSettings2" connectionString="mongodb://..." />
</connectionStrings>

var customerRepoOnDb2 = new MongoRepository<Customer>(ConfigurationManager.ConnectionStrings["MongoServerSettings2"].ConnectionString);