Question

I'm using EF 6.1 Code First. I'm programmatically configuring the connection string at runtime like:

myContext.Database.Connection.ConnectionString = "Data Source=(localdb)\v11.0;Initial Catalog=MyDb;Integrated Security=True;"

This works fine, but only if I keep some boiler plate connection information in my app/web.config:

  <connectionStrings>
    <add name="MyDb" connectionString="Data Source=NOTUSED;Initial Catalog=NOTUSED;" providerName="System.Data.SqlClient" />
  </connectionStrings>

I suspect this is because I'm not providing the provider information. I am specifying the provider and defaultConnectionFactory sections (SQL Server / LocalDbConnectionFactory), but it doesn't seem to care:

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

If I remove the connection strings section, it attempts to attach to a mdf file that doesn't exist:

System.Data.SqlClient.SqlException: Cannot attach the file 'C:\My Project\App_Data\MyDb.mdf' as database MyDb.

Normally, the localdb connection string results in a path to c:\users\my_user\MyDb.mdf. So it seems like it's not using the LocalDb factory unless I've got the connection string section in my .config file.

How can I specify - on a per context basis - the providerName information that EF is getting from that connection string node? Or am I barking up the wrong tree here?

Was it helpful?

Solution

This may have something to do with the way you are constructing your connection. If you are using the default constructor on the DataContext, then it will attempt to find your connection string from the config file:

MyDbContext myContext = new MyDbContext() <- this uses the default constructor
myContext.Database.Connection.ConnectionString = "_conn_str_"

If you pass the connection string in the constructor, then you should not need the config file entry:

using (MyDbContext myContext = new MyDbContext("_conn_str_")) {
   // the above line should not need an entry in the config file
}

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top