Search code examples
c#entity-frameworkef-code-firstentity-framework-migrations

Entity Framework: How to set up new database connection and run all migrations?


I have developed a WPF app with a local SQL Server database using Entity Framework code-first.

After replacing my old connection string with the new one in app.config, how do I run all migrations to the new, remote database?

Do I need to change anything with the Entity Framework tag in app.config?

<entityFramework>
    <providers>
        <provider invariantName="System.Data.SqlClient" 
                  type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

To make it clearer: my problem is that now if I run Update-Database, I expect it to run all migrations that it doesn't find on the newly defined database server, which should be all as none exist yet on that new server. Instead, what I get is:

PM> Update-Database
No pending explicit migrations.

So it still looks at the old database even though I replaced the connection string.


Solution

  • Found the issue myself. The way I initially declared my DbContext class and constructor was as follows:

    public class MyContext : DbContext
    {
        public MyContext : base() 
        { }
    }
    

    Apparently, EntityFramework automatically finds the connection string from app.config. But when I changed that connection string, even though I did not change its name, EF didn't apply that change by itself. So I changed the constructor to

        public MyContext : base("mycn") // unchanged name of the connection string
        { }
    

    Only then did it apply the change. A bit weird to me but eh...