Best practice for using entity framework for post deployment database changes - asp.net

I am working on a ASP.NET Web Forms project which is expected to experience lots of database changes even after deployment.
Our preference was to use Entity Framework 5, and the Database First design paradigm. However, since we have to make lots of changes to the database even after deployment, if I use database first approach, then every time I update my database, I will have to delete my entire model and regenerate it. Is there any best practices to make this process less painful?

You should use Code First, so that you can use Migrations.
More specifically I'd use manual Migrations.
With manual Migrations you can create Migrations at any point in time. A migration has the following information:
a snapshot of the current model
a set of "instructions" to upgrade from the previous migration
a set of "instructions" to downgrade to the previous migration
Apart from the necessary Migrations, you should add a new Migration when you deploy your app. For example, you can create a migration called "Version 1.0", when you deploy the version 1.0 of your app.
When you finish each new stable version, you simply add a new migration, for it, like "Version 1.1" or "Version 1.2".
The interesting part of migrations shows up when you have a deployed application version and you need to upgrade (or downgrade) to a new version.
There are commands that let you upgrade (or downgrade) a DB from one particular version
to another particular version. You can do it directly specifying a connection to the DB, or create a SQL script which will apply the changes to the DB. For example, if you deployed the version 1.0 in a customer server, and you need to upgrade the software to version 1.2, you can do this:
Update-Database -SourceMigration "Version 1.0" -TargetMigration "Version 1.2"
-Script
This will create a SQL script which can be run on the DB to upgrade from version 1.0 to 1.2.
If you need help about any of the Migrations commands, simply type:
get-help Update-Database -full
(Update-Database is a command name, you can specify any other like Add-Migration)
It's possible that you need to specify the project where the model is in, the connection string name, the name of the project with the .config file or some other things, depending on the specified parameters, and the structure of the projects in your solution.
To get more info on migrations, read MSDN EF Code First Migration.
NOTE ADDED IN EDITION: there is a new DB initializer that can automatically migrate to the latest version when the application runs. I've worked in a real application, and it works like a charm.
ALTERNATIVE SSDT
If you don't want to follow the advice, you can use SQL Server Data Tools (which can be installed inside VS, or work as an independente application, depending on the version you're using).
The idea of this tool is that you can compare projects (which are DB schema snapshots) to existing DBs, and generate the scripts to change the DB to match the schema in the project. (In fact you can compare any combination ofr project and DB)
If you keep versions of your project in a CVS you can even check the changes from one verison of the project to other version of the project.
NOTE ADDED IN EDITION: a SSDT project is a set of scripts that can build the whole DB, including all the objects in its schema. You can create it from an existing DB or viceversa. Then you can keep comparing any combination of DBs and SSDT projects, as soruce or target, and create an apply the scripts neccesary to change each particular object which has changes. (The scripts are created to change the target so that it looks like the source, but you can swap source and target easyly)
This is an alternative solution, but Migrations are much more powerful because you can customize them, for example to fill a "master table" when creating it, to set the initial value of a new column, and so on. If you use SSTD you'll have to do all of that by hand, and carefully keep track of it. So I highly recommend using Migrations.

Related

How to update the state and schema in Cordapp?

In corda dev mode,
For Example I have created a state with 3 Params, also with Schema for the state.
I have build the project and running it.
Due to the business need to need to 2 more params.
Below are the points I have understood from the corda docs.
Change the state.
Change the schema
Change the contract
Contract and state upgrade flow
I understood the existing states are updated with the new contract constraint.
Will the schema's gets updated by itself during the start of the node by giving {runMigrations=true}
Need help.
Firstly runMigrations property is used only for Corda Enterprise and not for Corda Open Source.
Take a look at the node configs available in enterprise and open source.
https://docs.corda.net/docs/corda-enterprise/4.3/corda-configuration-file.html#database-properties-ref
https://docs.corda.net/docs/corda-os/4.3/corda-configuration-file.html
Performing state upgrades is handled differently in open source and enterprise.
In Enterprise version, the tables are created as liquibase tables and liquibase is used to perform autotmatic database migration.
In Open source, liquibase is not used and tables are created as hibernate entities.
To do a state upgrade, you can add the three new params to your state, build the new jar, replace the old jar with the new one, and hibernate will take care of adding these new columns to the table. One more point on this is that even Hibernate advises not to use Hibernate to modify schema/data migration, so I would recommend you to create your own sql script and run it on the database. (This is done automatically by liquibase in the enterprise)
With corda 4 using signature constraints upgrade is easy, replace old jar with new jar(new jar has to be signed with the same signature used fro signing old jar), start the node. So you do not have to do the complex contract upgrade process.

EntityFramework Core production migrations

How do I update the database for production? I've moved the connection string secrets out of the application. Our CI/CD pipeline handles the token replacement within the connection string "template" that remains in the appsettings, and developers won't have production database access.
I had expected to use automatic migrations, only to discover today that Microsoft eliminated that for EF Core.
Will I have to, every time, temporarily overwrite the connection string that normally specifies my local dev copy of the database? It seems that way, but it also seems very janky process to me, so I wonder if I'm missing something.
There seem to be a confusion of what automatic migration means.
Migrations consist of two parts:
generation from the model
applying to the database.
Migration generation in turn could be two types:
automatic - at runtime, current model is compared to model produced by the last migration, and if there are changes, it generates an automatic migration code.
manual - migrations are generated at design time using the design time tools (Add-Migration command). The auto-generated code can be modified. Modified or not, the migration is stored along with the application code.
Regardless of how migrations are generated, they can be applied at design time using the tools (Update-Database command) and/or at runtime.
What EF6 supports and EF Core have removed is the auto-generation. EF Core migrations cannot be generated at runtime - they must be generated at design time and stored with the application code.
Applying them at runtime is achieved with Migrate method called from some application startup point:
dbContext.Database.Migrate();
For more info, see Migrations and Apply migrations at runtime EF Core documentation topics.

Dynamic database reference in SSDT (dacpac) project

Is there a way where the database references in a SQL Server Database project (Dacpac) can be derived at run time?
We're building a product which uses Dacpac to deploy database objects.
Our product implementation teams also use Dacpac projects by adding database reference to the product Dacpac file and then adding their own additional objects to the project.
The problem we're facing is - every time the implementation needs to point to a newer product release version, the parent dacpac references in the implementation dacpac have to be changed manually to refer to the new file path of the new product dacpac (in the newer release). We've mutiple implementation teams and multiple database projects in each implementation.
Is there any way the database references (*.dacpac) in a database project can be derived at run time using a variable or parameter or something of that sort?
My understanding of your question is as follows:
You have a SSDT database project (see example image below), that has a database reference (similar to #1 below) with stored procedures and other db objects that access the reference database (similar to file #2 and code #3). You've 'built' the solution resulting in a DACPac and now you want to take this DACPac and reference other databases at deploy-time. Hopefully I understood your question correctly.
If so, then you can use the Publish Profiles feature to achieve this (similar to #4 below).
The code for this can be seen in my notes from my SSDT talk github project.
If you look specifically at the demo04 solution file, you will see that I have a DEV_MJE.deploy.ps1 PowerShell file and a DEV_MJE2.deploy.ps1 file. These scripts run MSBuild to build the DACPac and then use SqlPackage to publish DEV_MJE.publish.xml or DEV_MJE2.publish.xml respectively. Note, if you run this example on your machine, you'll need to add MSBuild.exe and SqlPackage.exe to your path, as well as modifying the TargetConnectionString in the xml files to an existing development database.
As an example of how this works...When I use the Publish Profile DEV_MJE.publish.xml, the resulting GetDataFromAnotherTable.sql file contains:
SELECT [SomeData] FROM [AnotherDb_MJE].[dbo].[AnotherTable]
Whereas when I use DEV_MJE2.publish.xml the resulting GetDataFromAnotherTable.sql file contains:
SELECT [SomeData] FROM [AnotherDb_MJE2].[dbo].[AnotherTable]
Notice the database reference in the second has changed to AnotherDb_MJE2.
For a good description of how Publish Profiles relate to DACPacs and SSDT Database Projects, see this web page. It also contains information on alternative ways to deploy beyond SqlPackage.exe.
Something else to consider
Note, that using file paths to version control a DACPac is not really the best practice. Consider the DACPac artifact as similar to a .Net DLL. It is the biproduct of a build.
As such, a better approach is to use NuGet and tools like Octopus Deploy to store, track, and deploy DACPacs. See the stackoverflow answer for a good description of how this works.
Hope that this helps,
Michael
Thanks for the followup comment, I think what you are trying to do is when you write and deploy your code be able to use different dacpacs depending on the project?
Each implementation team might have a different version of the shared dacpac deployed so you can't just put the files in a shared location and call the dacpac "Product_Latest.dacpac" or something, so everyone always gets the latest version.
".sqlproj" files are standard msbuild scripts and references can be managed using msbuild properties so you can technically change the reference at runtime. If you edit your .sqlproj file and add a property in the first <PropertyGroup> tag, I used:
<ProdDacpacVersion Condition="'$(ProdDacpacVersion)' == ''">v1</ProdDacpacVersion>
v1 is the unique name for the version folder - you just need something to identify the dacpac you want.
I put the property just after TargetDatabaseSet and IncludeCompositeObjects.
If you then find the reference to the dacpac and instead of
<ArtifactReference Include="..\..\..\..\..\Desktop\prod\v1\Database2.dacpac">
<HintPath>..\..\..\..\..\Desktop\prod\v1\Database2.dacpac</HintPath>
<SuppressMissingDependenciesErrors>False</SuppressMissingDependenciesErrors>
</ArtifactReference>
Use the property from above:
<ArtifactReference Include="..\..\..\..\..\Desktop\prod\$(ProdDacpacVersion)\Database2.dacpac">
<HintPath>..\..\..\..\..\Desktop\prod\$(ProdDacpacVersion)\Database2.dacpac</HintPath>
<SuppressMissingDependenciesErrors>False</SuppressMissingDependenciesErrors>
</ArtifactReference>
Then the reference will use the property to get the path of the dacpac. There are a few ways you can set the property, you could edit the .sqlproj file when you want to take a new version of read the property from a file or environment variable or something (i'll leave the msbuild fun to you!).
I would, as a standard, everytime the reference was changed either reload the project or restart visual studio - it won't take long and it will save lots of cursing :)
When you deploy the dacpac's, the deploy looks in the same folder for references first so just make sure you copy the right one into the bin folder when you deploy.

Entity Framework 7 commands clarification - migrations add vs. database update?

I'm working on an ASP.NET 5 app that uses Entity Framework 7 with migrations to alter the application's Microsoft Sql Server database.
I'm running into a few issues when I reach the migrations step, and I would like clarification on what the Entity Framework commands migrations add and database update do.
It's my understanding that
> dnx ef migrations add Initial
creates a C# file ending in the name Initial in a folder named Migrations containing code that will create tables based on the application model classes, and
> dnx ef database update
executes the code that will add those changes to the database. However, after the migrations add command, the database has already been created, and the console gives an error when I run the database update command, saying that the tables already exist.
From what I've read on different tutorials, it seems like migrations add shouldn't actually affect the database, and the changes would take place when you run database update, but it doesn't look like that's the case.
Can someone explain what each of these steps are doing and how they fit together? Thanks in advance!
dnx ef migrations add shouldn't create the database. I suspect DbContext.Database.EnsureCreated() is being called somewhere in your application code giving it this effect.

EntityFramework 7 - CodeFirst - SQLite - Manage DB using ApplyMigrations at runtime

I am well on my way to utilizing EF7 CodeFirst with SQLite...but really want to employ DB Migrations at runtime. This is a desktop application (Click-once deployment) meant to sync with a main database when connection is available, and provide offline data when no connection is present.
I have pulled down the nuget pre-release versions and all is working, except I cannot find any documentation of how to apply the migrations at runtime. I can successfully Add-Migrations and manually Apply-Migrations...but need a way to programatically Apply-Migrations at runtime.
I've also browsed the EF7 open-source project, but could not get anywhere there.
Versions I'm using: Latest Pre-release as of 9/15/2015
EntityFramework.Sqlite v7.0.0-beta7
EntityFramework.Relational v7.0.0-beta7
EntityFramework.Commands v7.0.0-beta7
...et al...you get the picture.
I am asking for help to apply runtime migrations...or what is the documented/recommended path for programatically maintaining a local/embedded db using EF7 CodeFirst SQLite?
UPDATE:
I went back to EF6 with SQLite but then found out that there is not SQLMigrationGenerator for SQLite.
EDIT:
I believe ApplyMigrations() method referenced in one of the notes has been deprecated. Searching the repository, there is no reference to "ApplyMigrations".
Today you can invoke the extension method Migrate on the DatabaseFacade.
This method is only available when the using Microsoft.Data.Entity statement is present. It comes from the RelationalDatabaseFacadeExtensions class that is part of the EntityFramework.Relational package.
Still have to find out how to migrate up and down from the API.

Resources