How to downgrade/rollback migration in Universal Windows Platform with Entity Framework using Package Manager Console? - entity-framework

I modified a property in the model and it turned out it is not supported by the version of SQLite. This is the error. {"SQLite does not support this migration operation ('DropColumnOperation'). For more information, see http://go.microsoft.com/fwlink/?LinkId=723262."}
So I decided to roll it back by using the command Update-Database Migration "MyFirstMigration" but an error shows up on the console which states Update-Database shouldn't be used with Universal Windows Platform apps. Instead, call DbContext.Database.Migrate() at runtime.. This code recommended is already the code executed at the first run of the application that generates the first error above.
I am really going into circle here. Can someone suggest how I can rollback/downgrade MySecondMigration ti MyFirstMigration?

Can someone suggest how I can rollback/downgrade MySecondMigration ti MyFirstMigration?
For the same DbContext, just execute Remove-Migration command on your package manager console, it will remove the last migration of this DbContext. It is your MySecondMigration which will be removed and only MyFirstMigration left.
Update-Database shouldn't be used with Universal Windows Platform apps. Instead, call DbContext.Database.Migrate() at runtime
For this, just as this error shown, DbContext.Database.Migrate() applies any pending migrations for the context to the database, include what Update-Database did (Updates the database to a specified migration). By testing on my side, for the same DbContext, every new migration is the updating based on the old one. DbContext.Database.Migrate() will apply all the migrations for updating. If you don't want the latest update, just remove it for roll back.

Related

Resetting Entity Framework Migrations then synchronizing schemas from previous migrations

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.

How to cope with "No data stores are configured"?

I am currently playing with beta4 of EF7 using the blank ASP.NET web project template.
After having kicked off the existing migration, resulting in the tables being created in the localdb, the following occurs:
Strangely, when I clean up the migration-folder, including removing ApplicationDbContextModelSnapshot.cs and I run
dnx . ef migration add twice, I get the following error:
dnx : System.InvalidOperationException: No data stores are configured. Configure a data store by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.
The second migration is not created. When I review the created migration it contains all tables whereas the database is already provisioned, so you should expect the migration being empty.
Then, when I remove the first migration and run the add migration command again more than once, all the migrations are correctly created, i.e. as empty files.
Can someone explain this to me? Is this expected behavior or is this a bug in beta4?
Tip for people coming from former EF-versions:
* Don't use the K command framework anymore.
* Don't use the Add-Migration cmdlets anymore.
Both have been replaced by dnx . (dot). (dnx = .NET execution environment)
Some references:
https://github.com/aspnet/EntityFramework/wiki/Entity-Framework-Design-Meeting-Notes---September-11,-2014
http://jameschambers.com/2015/05/project-k-dnvm-dnx-dnu-and-entity-framework-7-for-bonus-points/
Remove the constructor of ApplicationContext. It is a temporary workaround to enable deployment, but it interferes with the Migrations commands.

How to update database driven Code First EF model?

I have an EF code first model generated by reverse engineering an existing database - one of the supported core scenarios for EF 6.
I now have updates to the DB and I want to reflect those in the model, but I simply cannot find a mechanism to update the generated model. In the "old" EDMX world, I could update model from database, but I cannot see how to do this in VS 2013 with EF 6?
I have tried to run a migration against the new database but no changes were made to the POCOs.
To update your database in code first projects, do the following:
Find out the name of the database context by checking your source code, in the following steps I assume it is ConfigDbContext
Open PM console via menu Tools -> NUGET Package Manager -> Package Manager Console
Type the following: PM> add-migration nameofmigration -context ConfigDbContext PM> update-database -context ConfigDbContextNote: Replace nameofmigration by any unique name of your choice so you easily remember the changes. The migration code will be named with a timestamp and this name.
If you got a success message, open SQL Management Studio, connect to your database, or, if you have it already open, refresh and review the changes.
Note: If you're getting a message that you should update EF core tools, here is how you can do that. For example:
PM> Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.2.0
Replace the version number 2.2.0 by the newer version you get displayed in the warning.

Code First Migrations for a custom NuGet package can't be executed from main application

I have created a module to be included in a main MVC3 web application. The module is packaged into a NuGet package and it can be installed and uninstalled via NuGet. Both, the main site and the module use Code First, EF >= 4.3
To create the package I have another MVC3 site and all the functionality is inside an area, so to create the package I just pack the libraries, the views and all the needed files. Database Migrations work fine in the project and the package is created nicely.
Now I install the package in the main site via NuGet. This site is in another solution, and the solution has two projects:
MyProject.Web.UI: this is an Mvc3 project
MyProject.EntityFramework: this is a class library with all the models, dbContext for MyProject...
The package is installed correctly and the Area, the Area views and libraries are correctly installed.
The problem now is how I update the database? I've tried first to run "Update-Database" but I get the message:
"No migrations configuration type was found in the assembly
'MyProject.Web.UI'. (In Visual Studio you can use the
Enable-Migrations command from Package Manager Console to add a
migrations configuration)."
I've tried then to enable the migrations with "Enable-Migrations" but I got this other message:
"No context type was found in the assembly 'MyProject.Web.UI'."
I tried also just to run the site and see if the changes are automatically applied but I get the exception page with the typical message:
"The model backing the 'NugetPackageDbContext' context has changed
since the database was created. Consider using Code First Migrations
to update the database"
I don't know what to do to update the database with the required changes in migrations that come in the NuGet package. Any one could put some light here in this matter? I'm quite new to Migrations, maybe there are some configs to update the database if there is a change instead of running the commands in the console, I'm a bit lost.
Thanks in advance :)
Good news! It seems that I got it. I was looking for a way to make the NuGet package to update the database to the latest version.
Well, this package comes with an Admin controller, so I added a new action called Update:
public ActionResult Update()
{
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<MyPackageDbContext, MyPackage.Migrations.Configuration>());
return View();
}
In my Configuration class for the migrations I have:
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
I have to say that in my way to do all of this I've found a few strange behaviors. One thing that surprises me is this, I don't know if this is normal, read the secuence:
Package installed with new migrations but database not up to date. So if I access the EF this affected by this I get the exception about this. Ok up to this.
I go to my action /MyPackage/Admin/Update and run it. Apparently it runs. I go to the database and I don't see changes. Even the migrations table does not have a new row.
I access again the EF part that displayed the exception before (point number 1) and then everything goes through, database is updated and the migrations table shows the new line.
One thing that you have to notice is that the Configuration class is internal, but because this is a module I needed to be accessible from another assembly. I tried to make it public but I got some strange warnings/errors that I don't know if they are related. So in the end I kept it internal but used
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OtherAssembly")]
I've found a few of strange behaviors in Visual Studio with all this stuff of the NuGet packages, CF, migrations ... I don't know if these things are bugs, but all this thing took me two full working days.
I hope it is useful for any other that wants to create a CF NuGet package that is updateable.
In package manager console you will need to the Default project to MyProject.EntityFramework
You may also need to make sure MyProject.Web.UI is set as the start up project (in case there are multiple), then you can pass in the connection string into update command:
Update-Database -ConnectionStringName MyConnStringName
This should update the database correctly, unless there is data that will be lost.
If your DbContext is in MyProject.EntityFramework then the Default Project in the Package Manager Console needs to be set to MyProject.EntityFramework before you can use Update-Database.
I realize that this question is very old, but since I don't see this answer I'll throw it in anyway.
To perform migrations and such on projects or external references you can still use the same three command:
Enable-Migrations
Add-Migration
Update-Database
but you wil need to supply some additional parameters. For the Enable-Migrations command you will need to add the -ContextTypeName and optionally the -ContextAssemblyName commands like so:
Enable-Migrations -ContextTypeName MyProject.EntityFramework.NugetPackageDbContext -ContextAssemblyName MyProject
This will give you a migration configuration class in your current project. The other two commands will require you to specify this configuration class:
Update-Database -ConfigurationTypeName MyProject.Web.UI.Migrations.Configuration
Hope that helps

How to use Entity Framework code-first

I created some classes, and configured the connection string.
But still got an error:
Unhandled Exception: System.NotSupportedException: Model compatibility cannot be
checked because the database does not contain model metadata. Model compatibility
can only be checked for databases created using Code First or Code First Migrations.
Check the EF version you have, latest is 4.3.1.
You also need to configure a DbContext class. check this: http://msdn.microsoft.com/en-us/data/gg685467
i fixed it
by Run the ‘Enable-Migrations’ command in Package Manager Console.
Here is what worked for me if you are fine with deleting and recreating the database from scratch.
First, run the following commands from package manager console.
sqllocaldb.exe stop v11.0
sqllocaldb.exe delete v11.0
Next, delete the mdf and ldf files from the app_data folder of your project.
Here comes the critical part. Usually you will run update-database. If you do that the exception will still be thrown.
DO NOT Run update-database. INSTEAD directly run your project code. The EF will recreate the database.
These steps worked for me. Let me know if this helps you.