Home > Net >  How to apply Entity Framework migration scripts to restore a database in an existing ASP.NET Core We
How to apply Entity Framework migration scripts to restore a database in an existing ASP.NET Core We

Time:09-24

I have an existing ASP.NET Core Angular Web application with the usual flairs. It comes with set of migration scripts (e.g. 20151227555555_AddIdentity.cs, 20161227444444_AddCoreEntities.cs etc) in a Migration/ code folder, each has Up, Down, and BuildTargetModel methods.

then there is another folder called MigrationScript that contains the equivalent of table creation SQL scripts (straight-up CREATE TABLE...) for the various database entities.

I am used to running database management and recreation/restore via a database project that I can "publish". I am new to the EF Migration way of doing it, so how do I run those migration C# scripts to create the database?

CodePudding user response:

The fact that the C# migration scripts already contains Up() and Down() methods means they are ready to be applied. (Note: usually the Up and Down methods are created by the Add-Migration migrationname command).

Here is how to apply the C# entity framework migration scripts in an existing project:

  1. Create the empty database with the correct database name. The database name is usually defined in the aspsettings.json file under ConnectionStrings group. Open Microsoft SQL Server Management Studio, create an empty database with the correct name.

  2. In Visual Studio Solution Explorer, right-mouse click on the project that contains the Migration folder (where the C# migration scripts are located), choose Manage NuGet Packages... and look under Installed tab to see if Microsoft.EntityFrameWorkCore.Tools package is installed, if not go ahead install it. Because that is the package that contains the EF migration commands, i.e. Add-Migration, Update-Database etc

  3. With the Microsoft.EntityFrameWorkCore.Tools package installed in the project that contains the Migration folder, open the Package Manager Console via Tools -> NuGet Package Manager -> Package Manager Console menu options.

  4. At the Package Manager Console prompt, type the command Update-Database, then all of the migration scripts will be applied and the tables created in the local SQL Server database created in step 1.

  • Related