Migrations¶
The EFCore Module integrates seamlessly with Entity Framework Migrations.
Migrations are generated by using the efcore
CLI, and are executed
automatically by the EFCore Module according to configuration.
Migrations are mostly used to keep the database schema up to date, however they can also be used to seed data. Be careful when using migrations to seed data, since we normally want to keep data separated, either depending on the configured setup or the destination installation.
Using EFCore Migrations¶
To get started, let's generate some migrations using the EFCore CLI.
Make sure you have the EFCore Module configured with at least an entity.
Tip
Name migrations in PascalCase. They won't pass analyzers if not.
This command will generate a new migration called called InitialCreate
that
will be added to our project inside the Migrations/
directory. The tool will
try to discover a DbContext
to find all your entities and to associate the
migration to it.
If you have more than one DbContext
in the same project, you must specify for
which of them you want to add the migration entry. You can do so by adding a
--context
option to the command being executed, as follows:
Text Only | |
---|---|
Migrations with a separate persistence layer¶
Something worth mentioning is the fact that the DbContext
on which you want to
add the migration entry, must be discoverable by the tool. The tool will try to
build the IHost
of your project and try to find a DbContext
from the
application's dependency injection container. This implies that, if your
DbContext
is located in another project which doesn't contain a runtime (no
host is present), like a Suite Module, the CLI command will fail.
To overcome the previous limitation, you can take advantage of the --startup
parameter to specify the project to start the host. The example below shows how
to generate migrations when you have your infrastructure layer separated in a
different project.
Text Only | |
---|---|
When using the microservice
template, migrations can be generated by using:
Bash | |
---|---|
Executing migrations¶
The EFCore Module takes care of executing migrations for you. Currently, they can be executed at two different times.
None
: migrations won't be executed by the EFCore Module.Lazy
: migrations will be try to be executed every time aDbContext
needs to be created. Most likely on a per-request/per-message basis.Startup
: migrations will be executed during application startup. This is the default and preferred option.
Currently the configuration of migrations is done at the
PersistenceModuleOptions
and it's limited to configuring the behavior for all
DbContext
s.