Home > OS >  Detect whether model and database out of sync in EF Core 5
Detect whether model and database out of sync in EF Core 5

Time:11-10

I'm using the "Create and Drop" APIs since my model changes often.

After a model change, I call dotnet ef database drop, and on next run the system calls context.Database.EnsureCreated() to recreate the database. I could precede that with context.Database.EnsureDeleted() but I don't want to drop/recreate the database every time (it slows down the development "inner loop", and it'll hammer my drive).

There used to be an easy way (in old EF) to programmatically detect if the database and model are out of sync. There isn't such a built-in feature in EF Core. There are some ways (e.g., e.g.) but they are a few years old, unreliable (depend on internal features) and for older versions.

Is there a stable way - without using internal assembly features - to do this in v5?

CodePudding user response:

You can get EF Core to serialise your schema (context.Model) into a string using .Model.DebugView.LongView.

Then I would calculate a hash value from that string, and compare that hash to a value stored in a table.

Since EF Core doesn't expose a method to run a raw select query, particularly if you can't depend on the schema being up-to-date. You would either need to use SqlConnection directly to query the table.

Or construct your comparison as an insert / update statement so you can decide what to do based on number of rows affected. Since you're going to destroy the database immediately, side effects of that sql can be ignored.

  • Related