Question

I have multiple connection strings in Web.config (for databases that should all have the same exact schema), and my DbContext is initialized with a connection string dynamically:

public MyDbContext(string connectionStringName) : base(connectionStringName)
{

}

I do not have a default constructor for MyDbContext as it is meaningless in my case. I decide which connection string to use based on the Id value of each entity (custom sharding).

I'm trying to run enable-migrations for my DbContext, but I'm getting the following error:

The target context 'MyDbContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.

I've seen a sample implementation of IDbContextFactory like so:

public class MyDbContextFactory : IDbContextFactory<MyDbContext>
{
    public MyDbContext Create()
    {
        return new MyDbContext("connectionStringName");
    }
}

How is this going to help me? Isn't the connection string still hard-coded? How could I add migrations for each database?

Was it helpful?

Solution

And how about providing default constuctor for that DbContext and then when you call scripts add-migration and update-database you may use -ConnectionStringName and -ConnectionProviderName attributes to point to database you want to use.

By the way - enable-migrations script does not do much - it addes Migrations folder to your project and Configuration class. You might do it yourself.

OTHER TIPS

Best Soution is to use a separate file where you will mention list of Id values against a connection e.g in

<connectionStrings>
     <add name="MyConn1"
          connectionString="#your connection string"
      />

     <add name="MyConn2"
          connectionString="#your connection string"
      />

and then in

<appSettings>
      <add key="MyConn1" value="entity1,entity2" />
      <add key="MyConn2" value="entity3,entity4" />
</appSettings>

Then dynamically load your connection string in some global variable

public MyDbContext() : base(MyConnectionManager.connectionStringName)
{

}

You can do it using IoC as well. Look at the sample code.

https://github.com/aamir-poswal/CodeSample

Especially
- Bootstrapper.cs
- CRMContext.cs
- DatabaseFactory.cs which you need to customize in your context

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