Before anyone marks this as a duplicate, none of the questions similar to this addressed any of my concerns or answered any of my questions.
I am currently developing all the POCOs and data contexts in a library project, and running migrations from within this project. The database I'm updating is the development database.
What do I do if I want to create the current schema to a fresh, new database? I figure that all I have to do is to change the connection string in web.config and run Update-Database, correct?
While the live/production database is up and running, I want to add new columns and new tables to the schema, and test it out in development. So I switch back the connection string to the development database's connection string, and run Update-Database.
Going back and forth between two databases seems like I'll get conflicts between _MigrationHistory tables and the auto-generated migration scripts.
Is it safe to manually delete the _MigrationHistory tables in both databases, and/or delete the migration files in /Migrations (so I'll run Add-Migration again)? How do we manage this?
What do I do if I want to create the current schema to a fresh, new database?
- Yes, to create fresh database to the current migration level you simply modify the connection string to point to a database that does not yet exist and run update-database. It will run all the migrations in order.
As far as migrating to the Production database, I am running the update-database command with the -script switch to acquire the raw sql and then applying that script to the production database manually. This is helpful if you need to keep a record of sql commands run against the database as well. Additionally, you can generate the script explicitly from a specific migration to another specific migration via some of the other update-database switches.
Alternatively, you can create an Idempotent script that works from any migration by using the–SourceMigration $InitialDatabase switch and optionally specify an end migration with –TargetMigration
If you delete the _MigrationHistory tables you will have issues where the generated script will be trying to add columns that already exist and such.
You may find the following link helpful:
Microsoft Entity Framework Migrations
I would suggest having a separate trunk in your source code repository - one pointing to production and one to development to avoid risks of switching between the two in visual studio.
Me also had the same problem, even when using one and the same database - due to some merges in the repository, and the mix of automatic/manual migrations. For some reason the EF was not taking into account the target database, and calculating what scripts need to me executed, based on what is already in the database.
To fix this, I go to the [__MigrationHistory] table on the target database and get the latest migration name. This will help EF to determinate the state of the DB, and will execute just the scripts needed.
then the following script is run:
update-database -script -sourcemigration {latest migration name}
This creates update script that is specific to the target database (the connection string should be correct, as discussed in the other comments)
you can also use -force parameter if needed
this way you can update any database to latest version, no mater in what version you found it, if it has MigrationHistory table.
Hope this helps
My production and my developmental database went out of synch and it gave me endless problems. I solved it using a tool from Red-Gate to match up the databases. After using the tool, the databases were exactly the same but my migration was not working and I started to get odd errors i.e. trying to add tables/ columns that already existed etc. I solved that. I just deleted the migration folder on the local, recreated it, added the initial migration, updated the database and then matched the data of this migration file (local) to the one on the host (delete all the data in the migration file on the host, and add the same data that is on the local into the host). A more detailed explanation is at:
migration synch developmental and production databases
Related
I have been having trouble working with migrations and an Azure Sql Database for the past couple of weeks.
I run enable-migrations and a migrations folder with a congfiguration file is created.
I then run Add-Migration InitialCreate and a migration is created with empty Up() and Down() methods.
PM> Enable-Migrations
Checking if the context targets an existing database...
Code First Migrations enabled for project MyService.
PM> Add-Migration InitialCreate
Scaffolding migration 'InitialCreate'.
The Designer Code for this migration file includes a snapshot of your
current Code First model. This snapshot is used to calculate the changes to
your model when you scaffold the next migration. If you make additional
changes to your model that you want to include in this migration, then you
can re-scaffold it by running 'Add-Migration InitialCreate' again.
I deleted an old database from my App Service and created a new one. This is now being targeted in my Web.config:
<add name="MS_TableConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MyService-20180212689875.mdf;Initial Catalog=aspnet-MyService-20180212578997;Integrated Security=True;MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
I have a feeling my code is targeting the old database which has been deleted on azure but holds the tables for the objects I'm now trying to add.
Update:
Removed the data objects and created a migration and it has been populated with the Delete code for non-existent tables(which existed in my last database). Definitely an issue with pointing to the right place. Any ideas?
Pretty new to Azure so not sure where to look to try and fix this.
Any help appreciated!
After adding migration, remember to enter "update-database" in Package Manager Console, which command runs the Up method to create the database and then it runs the Seed method to populate the database.
I have a feeling my code is targeting the old database which has been deleted on azure but holds the tables for the objects I'm now trying to add.
According to the code you provided, you set the database in Local in web.config and delete the database on Azure, but you could populate data to the deleted database on azure. There is no possible to achieve it.
Actually, when you publish you Web App to Azure, you could pick on the "Excute Code First Migrations" in Visual Studio and check if the TestContext is the database connection that you use now.
Each time you get both of them and after migrations, you will populate the data to the latest the database on Azure. You could read this article to know the details about Code First Migrations and Deployment.
I am using Entity Framework 6.1.3 Data migrations along with code first.
I am in the process of resetting the migrations. I have deleted the migrations history table and created a new baseline snapshot of the current state of the db. Everything works fine on a new install with the following intializer:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<T>, Migrations.Configuration>(true));
However, how should one deploy this reset to our customers who have an existing database? This fails locally when i have an existing db with the error:
There is already an object named '*****' in the database.
Does anyone have a better approach when needing to reset migrations and synchronizing schemas of existing databases?
I set out thinking I needed to reset my migrations because previous developers on my team were not using the Add-Migrations script correctly. This was causing the following error:
However, I wasn't sure how that would work out for existing customers. I didn't realize that I was able to re-scaffold my migrations. After much SO searching and trial and error, I was able to save my migrations. I first migrated to a migrations that was in a good state.
It was important to use the fully qualified name given. After trial and error I found a stable migration. I verified this by running the following:
It would succeed if EF could fully reconcile. I also had to exclude from VS project, all the migrations following the recently targeted migration. Simple shift select, right click and exclude from project.
Then I added the next migration back to the project after i updated the database. I also used the fluent API to exclude all the model changes following the currently targeted migration.
Then I incrementally re-scaffold all the broken migrations.
Then at the very end I created an idempotent script of my schema up to this point. Using the following:
My migrations are now not complaining about model mismatch and I am happy.
This is my first question in SO, though i have been referring to questions posted for quite some time.
I was recently doing a code first migration for an existing database to migrate it to the latest version. My DB initializer was using the default strategy "CreateDatabaseIfNotExists" and I'm using SQL server 2012 express.
The following were the steps used to do the migration:
1. Enabled migrations with the older database v1 and corresponding code version cv1. Generated initial migration script with -IgnoreChanges option. Updated the database with this migration.
2. With the latest code version cv2, used the older database v1. Added migration to generate the actual migration script for the schema changes and updated database
This worked perfectly for an existing database and it got successfully migrated to the latest version.
But for a new database, the database gets created, but seeding was not happening. On debugging, I could notice that the migration scripts are getting executed first even before DB schema was created.
The migration scripts are failing since the tables being migrated have not even been added yet.
Note:
I have turned OFF AutomaticMigrationsEnabled for migrations.
Please note, a similar approach to the above was working fine for the earlier version of EF - 4.3 which i was using.
This is the code in App_Start:
Database.SetInitializer(new DBLayer.Models.MyDBInitializer());
using (MyDBContext db = new MyDBContext())
{
db.Database.Initialize(false);
if (!db.Database.Exists())
{
((IObjectContextAdapter)db).ObjectContext.CreateDatabase();
}
//Initializing membership APIs
MembershipInitializer.InstallServices();
In the above code, after db.Database.Initialize, migration scripts are executing where as tables are not yet added and hence error gets thrown.
On disabling migrations and creating a new database, things work fine again.
My questions are:
How can you control this sequence for executing migration scripts to first add the tables before executing migration scripts. What am I missing here?
When automatic migration is turned OFF which are the migration scripts getting executed first place?
Please advise. Please let me know if you need any more info.
There's a lot of articles on this topic and I've spent hours reading them today. It's so confusing - most of the articles seem to try to save existing databases and even migration history.
My databases were created initially by code first migrations. I really don't have any data that's important to keep. So I would like to just delete my databases and the .cs migration history files in /Migrations folder. Then run add migrations and update-database to recreate the databases.
From what I'm reading, this is not the way to do it? My confusion is partially due to the totally different procedures suggested and the extensive coding for many solutions.
Can I delete my databases and /Migrations/*.* (except for Configurations.cs) and essentially reinitialize Migrations?
Btw, I am using VS Web Express 2013, MVC5/C#, SQL Express 2012.
I regularly do this during the development phase of my projects, as long as you are happy to lose your data then it is fine to delete the database, and migration classes, the database will be recreated when you run update-database.
During early development phases, my approach is to utilise automatic migrations and just use update-database which means nothing is created in the migrations folder, so you don't have to manage the extra files.
Obviously this approach isn't good once you start deploying the database for real, where I personally wouldn't use automatic migrations.
To enable automatic migrations, run the Enable-Migrations –EnableAutomaticMigrations command in the Package Manager Console.
More reading:
http://msdn.microsoft.com/en-us/data/dn481501.aspx
http://msdn.microsoft.com/en-gb/data/jj554735.aspx
It looks like CodeFirst stops doing its homework when it doesn't have full control of the database (I suppose).
The scenario is a web site hosted on Arvixe.com (or I suppose any other shared hosting server), where I have to create databases only from their control panel (and NOT with Sql Server Management Studio, just to say...).
Once created an empty database, I register a connection in the web site, and I use it to generate database from poco objects like in:
add-migration m1 -targetdatabase myconnection
This generates correctly my FIRST migration, that I can apply without problems with
update-database -targetdatabase myconnection
The first concern, not too important, is that since the database is existing, it will NOT issue the Seed command, so I have to insert my first records by hand, but this is not a great problem.
Then I change my poco objects, and I need to update the database, but when I issue ANOTHER
add-migration m2 -targetdatabase myconnection
it gives the error:
System.Data.Entity.Migrations.MigrationsPendingException: Unable to generate an explicit migration because the following explicit migrations are pending: [201111081426466_m1]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
This is really strange, since if I look at the database, I can see even the table __MigrationHistory, but then it looks like it cannot recognize it...
Anyone with the same problem, or some good tip to where investigate?
Thanks in advance,
Andrea Bioli
I had this problem. I was able to resolve it by providing a connectionString and a connectionProviderName parameter to both the Update-Database and the Add-Migration commands.
If you have many projects in your solution with multiple config files, Package Manager seems to be confused. In my case, I had one project selected as the default project for Package Manager Console, but it was pulling the connection string from the Visual Studio solution default start-up project instead.