I have a scenario where we want to run some automatic end-to-end tests on our backend (which uses EF Core 7).
There is the backend component that exposes some REST API and connects to an instance of SQL Server DB.
There is the suite of automatic tests that run on a separate process and:
- executes REST call towards the backend
- connects directly to the same DB using again EF Core 7.
Moreover, we use Code-first Migrations for our EF Core 7 to keep the DB schema aligned and up-to-date.
Now the problem: the backend instance, at the startup, calls the EnsureCreated()
and the Migrate()
methods to make sure the DB schema is up-to-date.
Also the automatic test suite needs to verify the status of the schema and apply (optionally) the migrations that are lacking.
These two events can happen at the same time, and if this is the case, we experienced some cases in which one of the two processes threw an error for the incoherence schema between the two processes.
How do you usually solve this issue?
Thank you very much!
1条答案
按热度按时间gz5pxeao1#
First, you should never call EnsureCreated on a production database or any other database that you plan keeping up to date using migrations.
Microsoft documents this clearly:
Note that this API does not use migrations to create the database. In addition, the database that is created cannot be later updated using migrations. If you are targeting a relational database and using migrations, then you can use Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate to ensure the database is created using migrations and that all migrations have been applied.
Using only Migrate could resolve your problem. Anyway, it is a good practice to call Migrate as part