Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Connection String at Runtime in EF 6

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

like image 209
A.Ima Avatar asked Feb 04 '16 10:02

A.Ima


1 Answers

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())
{
}
like image 84
Mark Avatar answered Sep 30 '22 07:09

Mark