Code First Migrations not being executed - entity-framework

I got a problem. Somehow my CodeFirst Migrations are no longer executed.
Everything worked perfectly before but not it does not work anymore. I deleted all the database now and tried to redeploy it, but the database is simply not updated anymore.
Any help?
( I got the checkbox in the publishing wizard checked to deploy CF Migrations)

Ok I found the solution, so I will post it here if anyone else gets stuck here.
The Code First Migrations only get executed after a request is made. However, somehow my requests did fail because the database structure was not correct. So I could not do a request to execute the migrations, and therefor the database was not updated. So I created a simple dummy Request that just returns an OK status, and called it. This did trigger the migration and now everythign works.
Weird.

It is not working because you might have created/selected other connection in deploy wizard. Same is confirmed in the deployed connection string where you can see two connnection strings.
The second connection string is also referecened in EF seciton -
And, in the context you have used first connectionstring - public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) {}
Changing name here will solve your issue.

I use this to force the migration to run.
var db = new MyDbContext();
db.Database.ExecuteSqlCommand("select 1");
db.Dispose();

Related

Getting EF Context has Changed Error After Updating Site

I am having an issue where I am getting an error "context has changed since the database was created," but when I look at the migrations history table it is the latest migration. This is a test site, so I updated the database using a sql script I got by running this command "Update-Database -Script -SourceMigration: $InitialDatabase" I can't just delete the whole database and recreate it. Has anyone run into a similar issue like this? Currently, I am using EF 6.1.3.
Note: I used code-first for this, so it was not an existing database I am adding to.
The issue was that a new directory had been created for the site due to the domain name being changed. I knew the domain name had changed, but didn't realize the physical directory had changes. It was such a slight change I missed it when I was checking the application paths (an s was removed). So the problem was caused by pebkac (problem exists between keyboard and chair).
Try to set your Initializer to null in the constructor of your DbContext class.
Like this:
Database.SetInitializer<YourDbContext>(null);
ScottGu's Blog explains why this happens :
http://weblogs.asp.net/scottgu/using-ef-code-first-with-an-existing-database
Have you tried using this command instead of executing a script?
Update-Database -Force
If you have enabled auto migrations, this should pick up your code-first changes and deploy them. The force will allow columns which have data to be dropped etc.

EF Code first migrations not running after deploy to Azure

I have two folders for my migrations (AuthContext and UserProfileContext), each has their own migration and some custom sql to run afterwards for data migrations and whatnot.
This works fine when using package manager console. I
Restore from production
Run Update-Database -ConfigurationTypeName Migrations.Auth.Configuration
Run Update-Database -ConfigurationTypeName Migrations.UserProfile.Configuration
Then everything is very happy in the new database, migrations executed data shuffled where it needs to.
I tried to test out the migrations on publish piece by:
Restore production on dev database
Single connection string (all contexts use the same) pointed to dev database
Publish to azure web site
Checked the box for Apply Code First Migrations
Selected that single connection string
Okay it published fine; however, when I went to look at the database, nothing happened! It did not create the necessary tables, columns, or data moves.
TLDR; Code first migrations are not running after publish to Azure
Update 1
I've tried any combination of the below: only one single connection string so I'm guessing that's not the issue, and execute migrations is checked.
On publish the api runs but no database changes are made. I thought perhaps I needed to hit it first but I just get random errors when I try to use the api (which now of course relies on the new database setup), and the database is still not changed.
I've seen a couple references out there about needing to add something to my Startup class but I'm not sure how to proceed.
Update 2
I solved one issue by added "Persist Security Info=True" to my connection string. Now it actually connects to the database and calls my API; however, no migrations are running.
I attached debugger to Azure dev environment and stepped through... on my first database call it steps into the Configuration class for the Migration in question, then barfs and I can't track down the error.
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = #"Migrations\Auth";
ContextKey = "AuthContext";
}
Update 3
Okay, dug down and the first time it hits the database we're erroring. Yes this makes sense since the model has changed, but I have migrations in place, enabled, and checked! Again, it works fine when running "Update-Database" from package manager console, but not when using Execute Code First Migrations during publish to Azure
The model backing the 'AuthContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database (http://go.microsoft.com/fwlink/?LinkId=238269).
Update 4
Okay I found the root issue here. VS is setting up the additional web.config attrib for databaseInitializer on only one of my database contexts, the one not mentioned is in fact hit first from my app.
So now I have to figure out how to get it to include multiple contexts, or, combine all of my stuff into a single context.
The answer to this post is not very detailed.
This article explains what I had to do to fix a similar problem to this:
https://blogs.msdn.microsoft.com/webdev/2014/04/08/ef-code-first-migrations-deployment-to-an-azure-cloud-service/
I'll roughly describe the steps I had to take below:
Step 1
Add your connection strings to your dbContexts, in my situation, they were both the same.
Step 2
Add this to your web.config
<appSettings>
<add key="MigrateDatabaseToLatestVersion" value="true"/>
</appSettings>
Step 3
And add this to the bottom of your global.asax.cs / Startup.cs(OWIN startup)
var configuration = new Migrations.Configuration();
var migrator = new DbMigrator(configuration);
migrator.Update();
Solved! To summarize the solution for posterity:
Enable Code First Migrations only enables them for one base connection string per checkbox checked, regardless of how many contexts have migrations against that base connection string. So in my case I broke out the two in question into two different connection strings.
Then I was hitting other errors and identified that if you're changing the base connection string to the model backing asp identity you need to include (one time publish) the additional flag base("AuthContext" , throwIfV1Schema: false)
For anyone who has this issue and may have overlooked the following: be sure to check that you have correctly set the connection string in your Web.config file and/or Application settings on Azure. This includes DefaultConnection and DefaultConnection_DatabasePublish.
In our case the former was correct but the latter contained the wrong database instance because it had been carried over from an App Service clone operation. Therefore the wrong database was being migrated.

Deploying to Azure not running EF Code First Migrations

I am running Entity Framework with Code First Migrations. My new release adds a table, modifies a few tables, and run some scripts. This works perfectly when developing locally using update-database.
Upon deployment the new table was not created and I was receiving errors from my client. I attached the debugger to the deployed site to track through what was happening. It reached the controller, went through the normal flow, and upon hitting the first database call to the new (but not actually existing yet) table it hopped into the Configuration class for my migration.
internal sealed class Configuration : DbMigrationsConfiguration<myProject.api.AuthContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = #"Migrations\Auth";
ContextKey = "myProject.api.AuthContext";
}
So I'm thinking great, all should be well. It goes through all of these, returns to the initial database call, but then that call returns an error, pasted below
The model backing the 'AuthContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database (http://go.microsoft.com/fwlink/?LinkId=238269).
This is surprising since indeed I have enabled code first migrations! Using the standard enable-migrations and add-migration, which work perfectly on my local machine when I issue the update-database command.
1) How can I get my Code First migrations to run once deployed to Azure?
Update 1
Here are my publish settings. For some reason I do not have the checkbox option for: "Execute Code First Migrations" and am guessing that's the issue...
Huzzah! My update was the issue. I found from other SO posts that his happens sometimes. A Clean and Rebuild, followed by restarting VS, restored the 'Execute Code First Migrations' checkbox. Re-deployed and everything worked perfectly.
Have you checked these lines of code?
In your web.config:
<appSettings>
<add key="MigrateDatabaseToLatestVersion" value="true"/>
</appSettings>
In your global.asax.cs / Startup.cs (OWIN startup):
var configuration = new Migrations.Configuration();
var migrator = new DbMigrator(configuration);
migrator.Update();

EF6 + SQL Server CE + two contexts+ CodeFirst Migrations from code - Detect Pending Changes after Add-Migration

Entity Framework 6.0.2. .Net 4. I am trying to update SQL Server CE 4.0 database from code, so when a new version of the application is released, the database(s) are automatically upgraded.
There are two data contexts in the project and they are targeting two different databases. This is what I am doing to update one of them:
Private Sub UpdateDatabase(connectionString As String)
Dim config As DbMigrationsConfiguration(Of MainDBContext) = New DbMigrationsConfiguration(Of MainDBContext)()
config.TargetDatabase = New System.Data.Entity.Infrastructure.DbConnectionInfo(connectionString, "System.Data.SqlServerCe.4.0")
config.ContextKey = "MyProject.MainDBContext"
Dim migrator As DbMigrator = New DbMigrator(config)
migrator.Update()
End Sub
The message from the Update method is that there are pending changes so I have to either run Add-Migration or enable Automatic Migrations. However, Add-Migration has been run and when I do allow automatic migrations, Update tries to create tables which already are in the DB.
Running Update-Database works fine when called like this:
Update-Database -configuration MyProject.MigrationsMainDb.Configuration -Verbose
I checked that the connection string used in the UpdateDatabase function is same as the one in the config file (used by Update-Database). I also tried not setting the ContextKey property, but it made no difference.
Is there anything obvious that I am doing wrong? Why does the migrator thinks there are pending updates but Update-Database is fine...?
I made it working. I realized that instead of creating the "generic" configuration class I should create the configuration class which had been added to the project by Enable-Migrations command. So the code has been changed to the following:
Private Sub UpdateDatabase(connectionString As String)
Dim config As MigrationsMainDb.Configuration = New MigrationsMainDb.Configuration()
config.TargetDatabase = New System.Data.Entity.Infrastructure.DbConnectionInfo(connectionString, "System.Data.SqlServerCe.4.0")
Dim migrator As DbMigrator = New DbMigrator(config)
migrator.Update()
End Sub
And this change resulted in the configuration object having properties set up correctly. For example the MigrationsDirectory property, which was not set before to what it should be. This was probably the reason of the issue - the migrator not finding migrations (looking for them in wrong directory) and assuming that the whole model has to be applied to the DB.
After making this change, I still had a small glitch with a pending change. In Visual Studio a file looked like modified, with one extra (test) property in the class, but when I tried to remove the extra line, I got a message from VS like "edited on master", or something like that. I closed the file and reopened - the extra property disappeared. I guess it was something with git, checking out branches and VS not refreshing files properly? Not sure really. But once this line was no longer there and the modified code in place, the Update function started working fine.
Update now updates existing databases and successfully creates new ones. Great :)

EF5 connection string error only in production

When on my dev machine, all works perfectly. Even using production connection values (so even when I connect to production from the dev machine). I don't think it's a permission problem because I am using the same credentials, just using EF5 instead of linq2sql, as the previous version of the service that worked. Also, the sql-profiler does not show a failed login attempt.
Connection string is:
Data Source=MYSQLSERVER;Database=MYDB;Integrated Security=True;
The error is:
Invalid value for key 'attachdbfilename'.
I have logged the connection string being passed into the dbContext code:
Database.Connection.ConnectionString = settings.DbConnectionHourly;
This is a class that inherits from my real dbContext (which packaged in a dll) and the settings get injected. Again, this works in Dev but not in production (server 2008 r2, IIS 7.5, framework.4).
Turns out that entity framework was trying to be very smart, but it was giving a very un-smart error message. So by convention, if you don't pass the context name in as a constructor, entity framework will assume the classname as the name of the connection string. What it will also do (which I was unaware of), is in development it will automatically connect to and create a schema using the visual studio built in sqlExpress. So in development, everything worked because this 'automagic' creation succeeded and since I later changed the connection to a different database, I was none the wiser about what EF was doing under the covers (EF was doing the wrong things but the end result worked).
However, when the application went to production, there is no sqlexpress or any database on the webserver so the automagic connection/creation sequence failed. Now if the error message had any useful information in it, this would be obvious. But since I had never set an 'attachdbfilename', nor did it tell me what the value of 'attachdbfilename' was or any context or what it was trying to do, this made figuring this out that much more challenging.
The fix was simple:
public HourlyContext(ISettingsWrapper settings)
: base(settings.DbConnectionHourly)
{ }
Instead of setting the connection after the context gets created (the creation process will immediately try to work it's magic with it's built in conventions/defaults), I now set it immediately through the constructor.