Dbcontext: use other connection strings - Entityframework

Asked

Viewed 999 times

1

I have a file web.config with 4 connection strings. How can I put these connection strings in the class DbContext?

public DataContext():base("ConnectionString") // Essa é minha conexão padrão
{

}

How can I do the same using another connection?

  • You want each context to be initialized by a different connection?

1 answer

2

When you create connection strings on the web.config you pass names to them in the name property. To choose one in your implementation DbContext Simply pass the base class constructor the connection name as it is in the name property on web.config. It’s like you did, but with the name of the other connections.

EDIT: An example would be the following, you add on web.config the following connection string

<connectionStrings>
    <add name="Exemplo" connectionString="ConnectionString" providerName="Provider" />
</connectionStrings>

Whereas ConnectionString is your connection string and Provider your predecessor, which in case and SQL Server is System.Data.SqlClient. So in your context, you would do the following

public class ContextoExemplo : DbContext
{
    public ContextoExemplo() : base("Exemplo") {}
}

Hence this context will sweat the connection string with name Example you added. Each context would simply have to put what goes in the name property there and EF knows what to use that connection string.

  • could you give me an example.

  • @Lucasvianamunhoz, added an example, see if it helps.

Browser other questions tagged

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