Migrations
When you've defined a new entity or changed properties on an existing entity, chances are that you have to migrate your existing database. For this we use migrations from Entity Framework Core.
First you have to ensure that you've included the Microsoft.EntityFrameworkCore.Design package in your .csproj file. You can add it by running the following command:
dotnet add package Microsoft.EntityFrameworkCore.Design
Next, you have to tell Confinity that it should use your assembly for migrations. You can do that by setting the migrations assembly in the Confinity options like this.
var confinityOptions = new ConfinityOptions(new SqliteDatabaseProviderConfiguration())
{
MigrationsAssembly = typeof(Startup).Assembly
};
builder.Services.AddConfinity(builder, confinityOptions, moduleBuilder => { });
Now to create a new migration you then have to run:
dotnet ef migrations add <A NAME FOR YOUR MIGRATION> --context ConfinityDbContext
The .Net migration tool will now create the required migration scripts.
Install the Tools
To run the above command you need to have the Entity Framework Core tools installed. You can easily install the tools via the following command:
dotnet tool install --global dotnet-ef
Initial Migration
If you never a have created a migration before, the migration tool will create an initial migration. That means, that it creates SQL statements to create all the tables required for your db context and some tables might already exist. In that case, you might have to alter the migration script accordingly or you have to delete your existing database.
Best Practices
Create SQL scripts for database updates and apply them manually for larger applications.
Always create separate migrations for your changes and changes from Confinity. After a version update always create a migration to be safe.
EF Core migrations creates a
DbContextModelSnapshot.cscontaining the current model and is used to draw attention during merges for possible conflicts. Some times this file can be merged without conflicts even though the resulting model is invalid. The advice is to markDbContextModelSnapshot.csas a binary file in git. This always causes a conflict during merges. When a conflict rises:- Remove migrations up to the point of the conflict: dotnet ef migrations remove
- If the EF commands are not working to rollback because of the conflict, you can copy the content of the BuildTargetModel method inside the
*.Designer.csfile from the migration you want to rollback and replace the whole content of the BuildModel method in the*ContextSnapshot.cs. - Create a new migration with:
dotnet ef migrations add <A NAME FOR YOUR MIGRATION> --context ConfinityDbContext