Some notes on adding and removing migrations in Entity Framework core

EF Code First approach (Create class/es first)

 

Previous: EF Core UWP Sqlite Step by step  (embedded101.com)

Also: Entity Framework with UWP and SQLite: Referencing the Model (embedded101.com)

More coming

 

Scaffolding provides a quick way to generate the database CRUD operations in a standardized way, creating the necessary logic that lets your application interact with the database layer.

 

NB: You must set the class project as the target. when doing migrations

 

(1) To initially set it up you run

Add-migration <some label> in the PM Console

It adds a three  files to the class project, as ,cs file and a .Designer.cs  and

 

(2) If you add or change properties to the model you can issue further add-migration <label> commands

 

(3) You can remove migrations using remove-migration with no label

 

Note that the migrations are added as a stack. If you do three adds then if you do 2 removes you are back to the first one.

If you match three adds with 3 removes you have no scaffolding.

 

A new set of three files is added for each add, any previous ones remain.

The added files for the last migration are removed when you do a remove.

 

The .cs file will add any new tables and indicate any property changes (add/remove columns = add/remove properties)

When the app runs after migrations (up or down), the App constructor code db.Database.Migrate() implements the database changes.

You may/may not lose data at this point. Also Sqlite does support some of these migration changes (e.g. renaming table columns (I think is one)).

 

NB: If making major changes to the model, you may wish to remove all migrations then add a new one.

If doing so it may be prudent to set the debug when it runs to completely reinstall the app (ie remove previous app data) so you get a new database file.

 

NB: If when doing a migration up or down you get an error saying the UWP app can’t reference the class library, or viz, then close the solution in Visual Studio and then reopen teh solution, i.e. without needing to close Visual Studio.