Support for Multiple Database Names
Closed this issue · 3 comments
Not an issue, but more of a feature request.
It would be nice to have an attribute to specify a different database name/ connection string. Currently, the entities will only use the connection string of "MongoServerSettings" If I have 2 collections in different databases, I'm not able to specify this to MongoRepository.
I would like to do something like this:
App.config
<connectionStrings> <add name="MongoServerSettings" connectionString="mongodb://localhost/Application?safe=true" /> <add name="UserDatabase" connectionString="mongodb://localhost/Users?safe=true" /> </connectionStrings>
Then in the Entity file, specify the secondary connectionstring like:
[ConnectionString("UserDatabase")]
public class User : Entity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
}
The entity file would by default use "MongoServerSettings" connection string unless the ConnectionString attribute was used.
It's not an Entity's responsibility to know/determine where it's going to be stored; it's the repository's. The MongoRepository
class has a constructor overload in which you can pass a connectionstring.
App.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="connection_A" connectionString="mongodb://localhost/MyDatabase_A" />
<add name="connection_B" connectionString="mongodb://localhost/MyDatabase_B" />
</connectionStrings>
</configuration>
Program.cs:
using MongoRepository;
using System.Configuration;
class Program
{
static void Main(string[] args)
{
var repoA = new MongoRepository<User>(
ConfigurationManager.ConnectionStrings["connection_A"].ConnectionString
);
var repoB = new MongoRepository<User>(
ConfigurationManager.ConnectionStrings["connection_B"].ConnectionString
);
repoA.Add(new User { FirstName = "Janice", LastName = "Doe", Username = "Jane", Email = "jan.doe@example.com" });
repoB.Add(new User { FirstName = "John", LastName = "Doe", Username = "Joey", Email = "j.doe@example.com" });
}
}
public class User : Entity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
}
`
Thank you, Rob, I didn't realize the constructor took a connection string. I'll go that route and thanks for the quick reply!
You're welcome ;)