update the database from package manager console in code first environment

93,249

Solution 1

You can specify connection string via ConnectionString parameter:

Update-Database -ConnectionString "data source=server_name;initial catalog=db_name;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" -ConnectionProviderName "System.Data.SqlClient" -Verbose

Also you need to use this parameter with the same value for Add-Migration command:

Add-Migration Version_Name -ConnectionString "data source=server_name;initial catalog=db_name;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" -ConnectionProviderName "System.Data.SqlClient" -Verbose

Solution 2

I used

Enable-Migrations -EnableAutomaticMigrations -Force

then

Update-Database

And this migrated my changes (additional columns) while preserving my test data. I think this is the laziest option while prototyping.

Solution 3

Looks like you have multiple issues. Regarding not wanting to drop and recreate the database, that is determined by your database initializer. If you want to use migrations you change it to MigrateDatabaseToLatestVersion. http://www.codeguru.com/csharp/article.php/c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm

Second, it doesn't matter how many fields you change, they will be rolled into a single migration based on changes from the last migration.

Third, as the others have pointed out, it seems you have a connection string issue. While you can add that to Add-Migration and Update-Migration I would probably fix it in the application. I set mine in the constructor of my context which points to my config file (web.config for ASP.NET).

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext()
        : base("MyConnection", throwIfV1Schema: false)
    {
        Database.SetInitializer<ApplicationDbContext>(new MigrateDatabaseToLatestVersion<ApplicationDbContext, MyObjextContextMigration>());
    }
    ...

Solution 4

Where to put the connection string?

You do not need to specify it with every command in the package manager console. You can put it in appsettings.json in the project where your DbContext class (read "from DbContext derived class") resides.

{
  "ConnectionStrings": {
    "MyConnectionString": "Server=yourServer;Port=5432;Database=yourDatabase;User Id=yourDatabaseUsername;Password=yourDatabasePassword;"
  }
}

It will be used for migrations.

Important: If you have multiple projects in your solution, you must select the project in the 'Default project'-dropdown (in the Package manager Console) and you must set the project as your startup project (in the Solution Explorer).

Failing to do so, might cause the wrong appsettings.json to be used with an incorrect/different connectionstring.

This was my experience with EF Core 2.1 and probably applies to the other versions of EF.

Share:
93,249
vinodh
Author by

vinodh

Updated on July 12, 2020

Comments

  • vinodh
    vinodh almost 4 years

    Code First Environment

    I'm trying to update the database from package Manager console.If my Domain class change, I have to drop and create the database,Instead of dropping the Database how can i update the database.

    I have already try by reading some blogs in google.

    commands

    PM> Install-Package EntityFramework
    
    1. By using this command i install the Entity Framework successfully.

       PM> Enable-Migrations
      
    2. By using this command it created the Migration file in my project.

       PM> Update-Database
      
    3. By using this command , i may update the table but i have a Problem here.

    Error

    Specify the '-Verbose' flag to view the SQL statements being applied to the target database. System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

    Doubt is here

    Sometimes It may update if only one field changes in POCO Class. For example I have Updated the more number of Domain class ,How can i Update the Database from Package manager Console. Any Idea ?

  • vinodh
    vinodh over 8 years
    If i use this command i may able to update the database if changes in single POCO class . If i have changed more number of Domain calss Field , how can i update ?
  • vinodh
    vinodh over 8 years
    If i use this command i got following error . Scaffolding migration 'update1'. The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration update1' again
  • vinodh
    vinodh over 8 years
    ,I have checked this, first one is used to update the table but if we are using it will update the table if class is not exist only. Please check this.
  • user1019042
    user1019042 over 7 years
    best answer for my case!
  • dcp
    dcp over 7 years
    I didn't downvote you, but I got a compiler error when trying to use your snippet: The type arguments for method 'System.Data.Entity.Database.SetInitializer<TContext>(System‌​.Data.Entity.IDataba‌​seInitializer<TConte‌​xt>)' cannot be inferred from the usage. Try specifying the type arguments explicitly
  • Steve Greene
    Steve Greene over 7 years
    That can be corrected with Database.SetInitializer<ApplicationDbContext>(... or whatever your context type is. Mine works without it though.
  • Edward
    Edward almost 7 years
    Doesn't work for me. OUTPUT: Update-Database : A parameter cannot be found that matches parameter name 'ConnectionString'.
  • Marcus
    Marcus over 6 years
    A parameter cannot be found that matches parameter name 'connectionstring'.
  • Admin
    Admin over 6 years
    Downvoted, even though it won't show. No such option exists in Visual Studio 2017 !
  • Mike Devenney
    Mike Devenney about 6 years
    @Marcus - Try using -ConnectionStringName as the parameter. So, if you have a connection string in your config file named MyConnection your update-database command would look like this: update-database -ConnectionStringName MyConnection
  • RWC
    RWC almost 6 years
    Probably no need to specify the connectiomnstring with every command. Please see my answer ( stackoverflow.com/a/51287652/760777 ).
  • rsbarro
    rsbarro about 5 years
    Setting the startup project worked for me. Otherwise it was reading the appsettings.json file from a different project. Thanks for the tip!
  • jamheadart
    jamheadart about 4 years
    @RWC that's only for Core applications?
  • RWC
    RWC about 4 years
    @jamheadart: I am not sure about that.
  • Aquiles
    Aquiles about 2 years
    For Net Core apps (EF Core 5), the command is Update-Database -Connection <string>
  • Kirk Woll
    Kirk Woll almost 2 years
    @Aquiles, thanks for your comment! If I were you, I'd post a new answer talking about how to do this for EF Core 5. You'd get my upvote! :) (The point of SO is to provide visitors with the best answer right away, and because your comment is a comment instead of an answer, voters can't make that happen.)