Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Migrations for Database-first approach?

We're using Database first approach with EntityFramework. We've several customers, and when we deploy new product version, we're now applying DB schema changes "manually" with tools like SQL Compare.

Is there a way how EF Migrations could help to apply changes to customers DB automatically?

like image 425
Shaddix Avatar asked Feb 13 '12 03:02

Shaddix


People also ask

How do you do migration in db first approach?

Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.

What are the types of code first migration available in Entity Framework?

Automated Migration. Automated Migration was first introduced in Entity framework 4.3. In automated migration you don't need to process database migration manually in the code file. For example, for each change you will also need to change in your domain classes.

How does EF migration work?

EF Core compares the current model against a snapshot of the old model to determine the differences, and generates migration source files; the files can be tracked in your project's source control like any other source file. Once a new migration has been generated, it can be applied to a database in various ways.


2 Answers

As far as I know, EF Migrations is a product targeted at CodeFirst and doesn't support Database First operations.

CodeFirst assumes that you will never make any changes manually to the database. All the changes to the database will go through the code first migrations.

like image 119
Paul Avatar answered Oct 14 '22 21:10

Paul


I think there is! You need to continue your way through the code first.

To do this, Suppose that you have the following DbContext that EF Db first created for you:

public class MyDbContext : DbContext {     public MyDbContext()         : base("Name=DefaultConnection")     {      }      // DbSets ... } 

change that to the following to start using code first and all magic tools of it (migration, etc.):

public class MyDbContext : DbContext {     public MyDbContext()         : base("YourDbFileName")     {      }      // DbSets ... } 

It causes that EF creates a new connection string using SQL Express on your local machine in your web.config file with the name YourDbFileName, something just like the early DefaultConnection Db first created.

All you may need to continue your way, is that edit the YourDbFileName ConStr according to your server and other options.

More info here and here.

like image 20
Amin Saqi Avatar answered Oct 14 '22 23:10

Amin Saqi