EF-Core - Database first migration

Viewed 4774

I'm wondering if there's a standard way of handling migrations when using EF Core database-first.

Every time I make change to the database I run this in the CLI:

dotnet ef dbcontext scaffold "Data Source=(local);Initial Catalog=myCatalog;Trusted_Connection=true;" Microsoft.EntityFrameworkCore.SqlServer -o Models -f

The problem with it overrides every change I made in other entity and in the dbcontext, for example I have an interface of Id for each entity, when I scaffold I later need to add this to the entity again, is it possible sync the project with the database or maybe just the specific entity?

Another problem is that I recently had to change the defaultDeleteBehavior of the entities from DeleteBehavior.ClientSetNull to DeleteBehavior.Cascade so now every time I use the scaffolding approach I need to change manually 100+ entities in the OnModelCreating method.

2 Answers

You don't really have database-first in .Net Core. So what that means is that the scaffold command is just there to get you up and running in a code-first project where you have an existing database.

What this means for you is that you have to decide where you're going to be making your changes:

a) The Database, or

b) The Data Access Project

Either of those options are valid, but you have to pick one and stick to it.

If you're making changes in the DB, you will have to ALTER all your tables and add the ID field to them, then run the Scaffold command again to update your model.

If you're making changes to your entities in the DA project, then you have to add an EF Core Migration each time you change a bunch of things.

In both those cases, you want to include the DB updates as part of your deployment, either via a bunch of SQL scripts, or by making the application perform a DB migration on Startup.

But what you should NOT be doing is trying to change things in both places. That's how you break deployments.

Yes, you can limit which tables are reverse engineered by specifying schemas and tables.

The --schema option can be used to include every table within a schema, while --table can be used to include specific tables.

Try like below to update only Foo table. Click here for more detail.

dotnet ef dbcontext scaffold "Data Source=(local);Initial Catalog=myCatalog;Trusted_Connection=true;" Microsoft.EntityFrameworkCore.SqlServer -o Models -f --table Foo
Related