Reputation: 266
I mostly use my dbcontext with using statements like this:
using (var context = new MyContext())
{
}
But I later had to add a project with a function to change the database. I found out that I could change my dbcontext constructor to this:
public MyContext(string connectionstring)
: base(connectionstring)
{
}
I made a class with a property for the connectionstring:
public static class DbAccessor
{
public static string ConnectionStringForContext { get; set; }
}
I set this property in the beginning and my using statements look like this:
using (var context = new MyContext(DbAccessor.ConnectionStringForContext)
{}
It works, but my connection string is now everywhere and I feel like I should not do that with connection strings. Is there a better way of doing this? What would be the best way to handle my Connection Strings if I want to change them? Should I stop using these using statements?
I've seen this question: Entity Framework change connection at runtime
But the difference is, that I have a functioning solution, but I don't want to have my connection string everywhere. If I used that extension method inside every using statement. It would almost be like my solution just one line more in every using statement...
Upvotes: 5
Views: 6636
Reputation: 1497
If I have understood you correctly you need to be able to support your application connecting to more than one database. You can do this pretty much as you are but have say two properties on your DBAccessor
class, remove the set and get the relevant connection from your config, that way your config is always maintained in the application config.
public static class DbAccessor
{
public static string ConnectionStringForDBOne { get { return ConfigurationManager.ConnectionStrings["DBOne"].ConnectionString} }
public static string ConnectionStringForDBTwo { get { return ConfigurationManager.ConnectionStrings["DBTwo"].ConnectionString} }
}
Then add some static creators to make life easier:
public MyContext(string connectionstring)
: base(connectionstring)
{
public static MyContext CreateContextDBOne()
{
return new MyContext(DbAccessor.ConnectionStringForDBOne);
}
public static MyContext CreateContextDBTwo()
{
return new MyContext(DbAccessor.ConnectionStringForDBTwo);
}
}
Then use them in code:
using (var context = MyContext.CreateContextDBOne())
{
}
using (var context = MyContext.CreateContextDBTwo())
{
}
Upvotes: 2
Reputation: 1371
You could try a static factory method (or factory class whichever you prefer) on your context which uses the connection string like so:
public class MyContext : ...
{
public MyContext(string connectionstring)
: base(connectionstring)
{
}
public static MyContext Create()
{
return new MyContext(DbAccessor.ConnectionStringForContext);
}
}
and then you can create your context like so:
using (var context = MyContext.Create())
{
}
Upvotes: 3