We are starting a new application with with .NET Core, EF Core and Postgres - we're really liking the migrations :-)
However, I've found a problem that I can't figure out how to work around. In some of our migrations, we use the DbContext to load records, run some business logic, and resave the records. We also run database.Context.Migrate() when the web server starts, so it always runs.
This all works fine (so far).
Unfortunately it works right up until the model is changed at a later point. Consider the following migration order:
Create
Customer,Order, andOrderLinemodels. Add the schema migrations to load the structuresA business rule changes, so we need to set a value on the
Orderrecord based on some business logic . We create a data migration where we load theDbContext, run the code, and runSaveChangesAsync()At this point, everything is fine.
We need to add a schema migration with a new field to the
Customerrecord.
Here, things break. If the database has not had migration 2 applied, the Migrate() command errors as when applying migration 2, EF is trying to generate a select statement that includes the new field in 3.
I'm not sure where the problem actually is in the process though: should we not be using the DbContext in the migration (and hand-code SQL statements)? Should we be explicitly be doing projections on every record read so that we know exactly what we're doing?
Something else?