One of the most complex things to manage in the development of any application, from simple client applications to the most complex enterprise solutions, concerns the management of persistence.
In the .NET environment some of this complexity can be managed through the use of migrations implemented internally in Entity Framework.
Often this feature is seen as a utility purely for the use of developers to update the database schema.
When we think we have arrived at a stable situation we drop all migration and start from a clean situation.
This is a phrase that I have heard really too often from many colleagues, used more or less consciously, often the reasons that lead to outsourcing in this sense is an insufficient analysis of the problem that generates many changes, even destructive changes, of the databases.
Other times more conscious and driven by a desire not to keep versions earlier than the one we assume will hold “real” data, often this coincides with the first production release.
Actually, what the tool offers us is an incremental versioning system something that goes far beyond the scope of the developer by also involving DBA or more properly DBRE.
How can I perform operations on the data?
This thing is one of those operations that is not possible to instruct in a migration through the APIs that Entity Framework makes available to us as it is very domain dependent and trying to formalize this through APIs would have been very complex if not impossible and it is for these cases that the loophole for running raw SQL scripts was provided.
The example just given might turn the nose up at both categories.
To the developers because there are strings within the source and to the DBRE because they would find themselves working “inconveniently” without auto-completion.
How to make both worlds happy?
One feature of the tool is to generate partial classes that are matched with content classes in files named
which hold the other part of the partial class decorated with an attribute identifying the context to which it is bound and one representing its identifier.
We can then think of extracting the SQL script within a file with the
.sql extension and exploit the runtime migration identifier to read it and integrate it within the migration.
Our migration will then have this content
and the SQL script can then be read from the path relative to the execution directory
Let us also remember to add the instruction
.csproj to instruct MSBuild to publish the files to the target folder.
As always you can view the full sample design at