Migrating changes to DB - c#

I'm developing a web app in ASP.NET with Entity Framework and a SQL Server database.
I'm using Code-First approach. Until now everytime I made a change to the database schema (added tables, changed tables rows (add or remove)) the database was recreated. Since it was not a live version yet.
Now, I will deploy the application, while I continue to develop it.
How should I proceed to update a live version of the database with the changes I make locally? That, without losing data.
So, per example, I create a new table and a add or remove a few rows in another tables with a code first approach. Everything is tested and working and now I want to update the live version. How would I proceed?

You need to use the Code First Migrations, check out this Link to MSDN
Code first migrations will take the current state and make it 'Initial Migration', all changes from then on are scripted as incremental updates. Your change flow should look like this:
Make change (add table through classes, etc etc)
Generate a Migration
Run the Migration
Test the Change
Deploy the change to the live system
When you deploy the change, in your publish settings you can inform it to run the migrations on application start up, or on request.

Related

Entity Framework code-first and existing database

I'm working on an application with asp.net mvc that supports install, remove plugins.
When I want to install a new plugin I have an Install method that registers new routes and ...
For database, I use a code-first approach for creating database and every plugin has it's own context class.
My question is: when I want to install a new plugin, I need to create additional tables in my existing database, or create a new database if the database does not yet exist. And if those tables are already there, nothing should be created.
How do I achieve this?
Thanks in advance
Code First Migrations has two primary commands that you are going to become familiar with
Add-Migration will scaffold the next migration based on changes you
have made to your model since the last migration was created
Update-Database will apply any pending migrations to the database
When you develop a new application, your data model changes frequently, and each time the model changes, it gets out of sync with the database. You have configured the Entity Framework to automatically drop and re-create the database each time you change the data model. When you add, remove, or change entity classes or change your DbContext class, the next time you run the application it automatically deletes your existing database, creates a new one that matches the model, and seeds it with test data.
This method of keeping the database in sync with the data model works well until you deploy the application to production. When the application is running in production it is usually storing data that you want to keep, and you don't want to lose everything each time you make a change such as adding a new column. The Code First Migrations feature solves this problem by enabling Code First to update the database schema instead of dropping and re-creating the database.
I recommend to have look following link which makes you more clear about your problem.
https://msdn.microsoft.com/en-us/data/jj591621

Migrating Entity Framework without Migration Files

I am working on a project which is using Entity Framework code first for its data structure. It was created with code first, but was never migrated again and only has its initial migration data stored. Since then, the database has been modified directly through server explorer in VS2015.
There is no migration information about any changes and the database has critical information which I cannot lose.
Which brings me to my Questions.
If I create a new migration and update the database from it, will it wipe all changes which were not recorded in migrations and still leave the changes which were made as well?
The details of your question is a bit sketchy, but I will make some assumptions in order to help you along. Please correct where I am wrong.
I assume that you want to keep the data which resulted from the changes which were effected directly to the database, but you do not want to keep the changes that was effected to the database - in other words: keep the data but not the datastructures.
My advice is as follows
Always perform a full backup of your database when you are about to do something you are uncertain about.
If you can identify the tables you want to update, you can always use the SELECT INTO statement to create a quick backup of the specific tables only. These tables will not be removed when you do a EF database migration unless you explicitly script the deletion.
You can build the SELECT INTO statement into your EF migration via the Sql() method, or you can manually run the command against the database.
More information:
Click here to learn about EF code first migrations in general
Click here for a comprehensive code first migration reference
I believe following two posts will help you.
EF 4.3 Migration Walkthrough : http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx
update:
Code First Migrations with an existing database
https://msdn.microsoft.com/en-us/data/dn579398.aspx

how to detect the new database when change database in asp.net mvc4

The problem that when i change the new database then application not detected the new database and retreive error
The model backing the 'DBContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database (http://go.microsoft.com/fwlink/?LinkId=238269).
but i don't using Migrations so i don't update-database by Package Manager Console
How can i fix this problem?
Actually it does detect changes in your database. The database differs from the model. The error message.
This error is thrown when the hash stored in the migrations history table does not match a calculated hash. (Have a look at __MigrationHistory table, might be under system tables)
If you delete this table the check is essentially disabled. You can achieve something similar by adding Database.SetInitializer<YourContextType>(null) to the startup of your application. The latter disables database creation from within that application, so if you want to create the database by code, you would need to do this from a separate application (for example an console app). I prefer to go this way for web applications.
Secondly: if you change your database manually (change columns, add tables, etc.) you need to adjust your model. So for each DDL statement, change your code.
If you are not using code first, you could update your existing model in the designer.
I ran into this problem when I first started with code first and mvc. the answer below is absolutely correct but you should go to the ASP.net website and do some tutorials on code first migrations. you need a better understanding how update database and initialize and migrations work.

Versioning support for Entity Framework auto generated T-SQL?

I have a solution which uses Entity Framework model first approach.
The problem I am facing is that whenever I change something on a table, add a column or change a relationship,I right click and go for "Generate Database from Model", which re-generates ALL the code for the solution even if I just changed one table..and that generated code is useless for a production database since it drops every table and then re creates them..
I am wondering, isnt there be an option just to generate the T-SQL with the changes I made ? Otherwise model first would be useless after your app goes into prod.
I am using entity framework 5.0
Personally, I would suggest you to use Red-Gate SQL Compare when you need to sync your databases at Production environment.
This tool helps you to compare and synchronize databases using sync scripts without losing data (it will alert about if so) and its UI is just awesome.

Explanation of Migrators (FluentMigrator)?

Could someone explain the concept of Migrators (specifically fluentmigrator)?
Here are the (possibly confused) facts Ive gleaned on the subject:
Is it a way to initially create then maintain updates for a database
by way of versioning.
The first migration (or initial version of the
database) would contain all the tables, relationships and properties
required (done either fluently or using a chunk of sql in a script).
When you want to push a change to a database, you would create a new
migration method (Up and Down), something like add a new table or modify a field.
To deploy one of these migrations, you would use a
command line specifying the dll containing the migration, the
connection string and the required version.
If you had a rather complex set of data models, wouldn't it be rather difficult and time consuming to create a migration definition for all of that?
I know with nHibernate/fluent you can easily generate tables for a database without having to define anything other than the models and map files. Is there a way to make this configuration compatible with the Migrator/Versioning?
When nhibernate/fluent is in charge of generating a database, I do not necessarily need to define every thing aspect of the tables. Its done either via convention or via the mapping files. With the migrators I would need to define this level of detail?
Lots of questions here. I'll answer the questions with a focus on FluentMigrator.
Is it a way to initially create then maintain updates for a database
by way of versioning.
FluentMigrator is a way to version control your database schema. Everyone does it in some way. Either manually, with sql scripts, with a tool like SqlCompare or a Visual Studio Database project. All these methods are easy to mess up. It is so easy to make a mistake when releasing a new version and cause the system to crash. Migrations is a better way to handle this.
FluentMigrator allows you to define a change to the schema as code and this is usually checked in to your source control with the other code changes. Meaning that you can say version 1.XX of your system should have version 123 of the database. It means if you roll back your code to the previous version you also know what version of the database to rollback to as well.
It can be used both to create the database schema from the beginning or to start with version control of the schema for an existing database.
A Migration is a way to describe a change to your database schema. FluentMigrator creates a VersionInfo table and stores the unique id (version number) of the Migration after is has been applied.
For example, if I have two Migrations one with Id 1 and one with Id 2. If then I execute the first Migration then Id 1 will be stored in the VersionInfo table and I can look there and know that the version of the database is 1 and that version 2 has not been applied yet.
Being able to know which version the database schema is very useful when pushing changes from Test to Production or if you have multiple copies of the database in Production. For example, I have a customer with offices all around the world and each office has their own copy of the database and all of them are on different versions. Without knowing the database version it would be very difficult to update them safely.
Most of the time I do not need to actually look in the VersionInfo table, FluentMigrator handles this automatically. It compares the assembly with Migrations to the VersionInfo table and figures out which changes have not been applied yet and then executes those.
The first migration (or initial version of the database) would contain
all the tables, relationships and properties required (done either
fluently or using a chunk of sql in a script).
The starting point is up to you. You can have a first migration that is an sql script that you have generated from the current database. You could could also use one of the contrib projects like FluentMigrator.T4 to generate a Fluent Migration. Or you could just decide that the existing database is the starting point and save a copy of it to be able to restore it as version 1.
I have introduced FluentMigrator to a lot of legacy databases without any major problems.
When you want to push a change to a database, you would create a new
migration method (Up and Down), something like add a new table or
modify a field.
Yes, Up is used to apply the change specified in the Migration and Down rolls it back. So Up could be to create a table and Down could be to drop the table.
To deploy one of these migrations, you would use a command line
specifying the dll containing the migration, the connection string and
the required version.
There are three runners available to execute migrations. The command line runner, the Nant task and the MSBuild task. There are usually executed as part of a build script.
The MigrationRunner class can also be used in code. You might do this if you wanted to build your own runner or if you have other needs (like building databases dynamically or automatically updating the database if a new migration is added.)
If you had a rather complex set of data models, wouldn't it be rather
difficult and time consuming to create a migration definition for all
of that?
I have mostly answered this already. It is usually quite easy to generate an sql script for a database. For Sql Server it takes less than a minute to generate the script even for large databases. This script can be saved in a .sql file and executed as the first migration using the Execute.EmbeddedSqlScript expression. It works a treat.
I know with nHibernate/fluent you can easily generate tables for a
database without having to define anything other than the models and
map files. Is there a way to make this configuration compatible with
the Migrator/Versioning?
At the moment, there is no such integration and in practise I, at least, don't miss it. There was some discussion about connecting Fluent NHibernate and FluentMigrator but it would be a lot of work. It would enable scaffolding to generate changes to the model like EF Code First migrations do. It's not on the roadmap at the moment however.
When nhibernate/fluent is in charge of generating a database, I do not
necessarily need to define every thing aspect of the tables. Its done
either via convention or via the mapping files. With the migrators I
would need to define this level of detail?
Yes, you would need to define at that level of detail. FluentMigrators' migrations are a DSL (own little language) for defining schema changes that are translated to sql. You can write sql directly as well using the Execute.Sql expression. Entity Frameworks migrations have that sort of integration which has both advantages and disadvantages.
Check out the wiki or one of the tutorials here, here (part 1) or here (part 2) for more help getting started.

Categories