Is it possible to instantiate a database connection manually using the Entity Framework?

Asked

Viewed 41 times

1

I would like to manage my connections manually so that users can inform the server address, but Entity creates the connection string directly in the config file, the only way would be to change that file every time.

But I wanted to do this through code, as if I were instantiating a connection manually or just informing the connection string via code without modifying the settings file. It is possible?

1 answer

1


Yes, it is possible.

One way to do this is to pass as context constructor parameter. One of the manufacturer’s overloads accepts a string.

With this approach it is possible to work in two ways: 1) keeping all connections in the file web.config and build the context by passing the connection name as parameter; and 2) pass as constructor parameter to string full-connection.

public class SeuContexto : DbContext
{
    public SeuContexto(string nameOrConnectionString) : base(nameOrConnectionString)
    {
    }
}

And the use could be something like

var context = new SeuContexto("uma string de conexao gigante aqui");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.