3

I'm trying to use EF 4.1 with Code First POCO objects against a legacy database. I have many similar databases all with the same schema, and I need to decide which one to connect to at runtime.

All the examples I've seen show to put your connection string in the App.config or Web.config. This won't work for me since I need dynamic behaviour.

What object/properties can I manipulate to control the DB settings for my DbContext?

codemonkey
  • 1,213
  • 2
  • 14
  • 31

1 Answers1

3

DBContext has a constructor that accepts a DbConnection instance, which you can spin up using the appropriate factory class.

I do this sort of thing in one of my apps:

_context = new MyDbContext(
    new SqlConnectionFactory(Properties.Settings.Default.MyConnectionString)
        .CreateConnection("DatabaseName"));

So I can read the connection string at runtime and pass it to the SqlConnectionFactory class, which will give me a new connection using that.

I'm not sure that the "DatabaseName" parameter is used in this case, since it's in the connection string anyway. To be sure, I've made sure they're the same.

Matt Hamilton
  • 200,371
  • 61
  • 386
  • 320