Connection String in Entity Framework 6

By FoxLearn 11/9/2024 2:20:59 PM   15
In Entity Framework 6 (EF6), the connection string is typically specified in the App.config or Web.config file of your project.

Entity Framework 6 (EF6) uses LocalDB by default

When Entity Framework 6 (EF6) is installed (typically via NuGet), it automatically adds certain default settings to the Web.config or App.config. These settings configure EF6 to use LocalDB by default for database connections.

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
</entityFramework>

When you run an Entity Framework 6 (EF6) project for the first time, a new database is automatically created under the LocalDB instance. By default, the database is stored in the (LocalDB)\MSSQLLocalDB instance (for SQL Server 2014 LocalDB). The database name is generated by concatenating the project's namespace and the DbContext class name.

How to Use SQL Server instead of LocaDB in EF6?

To use a SQL Server instance instead of LocalDB in Entity Framework 6 (EF6), you need to make the following changes:

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
    <parameters>
		<parameter value="Data Source=.;Initial Catalog=myDb;Integrated Security=True;MultipleActiveResultSets=True;" />
	</parameters>
</defaultConnectionFactory>  

Update the defaultConnectionFactory setting to use SqlConnectionFactory instead of the default LocalDbConnectionFactory.

Provide the appropriate connection string to connect to your SQL Server instance (instead of LocalDB) under the <connectionStrings> section.

<configuration>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Server=.;Database=myDb;User Id=sa;Password=123@qaz;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

How to Specify the Database Name?

public class MyDbContext : DbContext
{
    public MyDbContext() 
        : base("MyDB")  // Specify the desired database name here
    {
    }

    public DbSet<MyEntity> MyEntities { get; set; }
}

In this case, EF6 will create a database named MyDB instead of the default MyNamespace.MyDbContext. This approach allows you to control the database name used by EF6, making it easier to work with more descriptive or customized database names.