0

I have a Web API project using Entity Framework using the default local database, how can I change it to use a connection string for a new database?

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="mssqllocaldb" />
        </parameters>
    </defaultConnectionFactory>
    <providers>
        <provider invariantName="System.Data.SqlClient" 
                  type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

Web config: https://pastebin.com/rKaJ8p6V

2 Answers 2

2

Here is a connection string example:

<connectionStrings>
    <add name="xxxDbContext" connectionString="Server=tcp:hostname,1433;Initial Catalog=xxxDb;Persist Security Info=False;User ID=sa;Password=xxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
</connectionStrings>

And then, you can use it this way, where xxxDbContext is your EntityFramework DbContext class.

using (xxxDbContext db = new xxxDbContext("name=xxxDbContext"))
{
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

You didn't mention why the code is at it is: if the name of connection string matches the name of the context class, then there's no need in base constructor call - as in @MofidMoghimi's answer.
1

In configuration tag in Web.Config file, use connectionStrings tag like this:

<connectionStrings>
<add name="[Your Connection String Name]" connectionString="Server=.;initial catalog=[your Database name];integrated security=sspi" providerName="System.Data.SqlClient"/></connectionStrings>

And your DbContext constructor class, use your connection string

public class DatabaseContext:DbContext
{
    public DatabaseContext():base("[Your Connection String Name]")
    {

    }


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.