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...