Is it possible to get Entity Framework to recognize previous migrations if you change your project namespace? - entity-framework

Let me break down the scenario:
I create my models/mappings using the code-first approach
I setup a database initializer for MigrateDatabaseToLatestVersion
I create a migration using add-migration
This creates a Configuration class like so:
namespace MyApp.Migrations
{
internal sealed class ConfigurationInfo : DbMigrationsConfiguration<MyContext>
{
}
}
I can run my code and the database will be automatically created with no issue.
Now I go in and change the namespace that my Configuration class lives under:
namespace MyApp.Data.Migrations // <-- new namespace
{
internal sealed class ConfigurationInfo : DbMigrationsConfiguration<MyContext>
{
}
}
I drop the database and rerun the code. I now get this message:
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
When I renamed the namespace that Configuration lived under it no longer recognizes any of the migrations that were previously created.
I did a lot of experimenting and when I set MigrationsNamespace equal to the old value in the Configuration constructor like so:
namespace MyApp.Data.Migrations
{
internal sealed class ConfigurationInfo : DbMigrationsConfiguration<MyContext>
{
public ConfigurationInfo()
{
AutomaticMigrationsEnabled = false;
MigrationsNamespace = "MyApp.Migrations"; // <-- this works
}
}
}
Now everything works, except all of the previously created migrations need to live under the old namespace in order to work, as well as all future ones (which get the old namespace automatically).
This workaround didn't really do what I wanted to do, which is be able to refactor my code and still have entity framework recognize my previous migrations.
What if the name of my project changes, but I have multiple installations out there that are depending on the MigrateDatabaseToLatestVersion database initializer to receive schema changes to my code?
Am I locked into using the same namespace for my DAL as soon as I enable migrations?

This was my own fault, I did the refactor by hand and thought that I had changed the namespace for all files in my project, but I forgot to expand the migration files and update the "designer" files as well!
When I set the same namespace between the configuration file, the migration files, and the migration designer files everything works great, and I can change the namespace at any time without EF losing track of the old migrations.

Related

Update-Database fails on production server

I've enabled migrations for my ASP.NET MVC project. Migrations work perfectly on localhost. However I get the following exception after deploying it to the server:
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
View Stack Trace
There are no pending migrations, though. Adding a new migration just creates empty Up() & Down()
What could be the reason it doesn't work on the server? I've tried deleting the migrations folder, re-enabling migrations, deleting the database, and let EF do it afresh. The tables get created, but I end up with that exception.
Update:
Another thing I noticed is, when I delete the migration folder but not the database, and enable migrations, it only adds a Configuration.cs file, when it's supposed to add another file too (initialcreate.cs)
This happens when you are doing tow different query on the same list of objects on the same time without using .toList
example :
you can create context and get a list of testObjects then edit one of this objects then save changes
var objectsList = context.testObjects.where(x=>x.whatever=true)
objectsList[0].whatever2="asd"
context.SaveChanges()
the above code will pass the compailer and it will fail while running, to solve this it should be as below
var objectsList = context.testObjects.where(x=>x.whatever=true).ToList()
objectsList[0].whatever2="asd"
context.SaveChanges()

Entity Framework 6 migrations odd behaviour

I am using EF6 Code First with migrations in a new project. I have used this in a few projects already without issue.
Now this new project is against an existing database.
I generated the standard Initial migration file, then deleted all the contents leaving just the Up() and Down() methods. This has worked for me in other projects, but not this time.
When I run update-database from the Package Manager Console, all works as expected.
PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No pending explicit migrations.
Running Seed method.
Then I execute the migrations from code (as needed in production) and I get...
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
I have been trying to get my head around this one for two days, and not getting anywhere.
I have even added another migration file called "stub" and it is generated blank. EF does not see any changes to my model (of which there are none), so it has nothing to generate. Yet the migration execution via code persists with the error that there are migrations pending.
I have attached a logger to the code execution of the migrations and the output is this.
Target database is: 'FMS' (DataSource: (local)\SQL2012, Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
And then I get the error message in my browser.
My configuration class
namespace FMS.Infrastructure.Repository.EF.Migrations.Stage
{
public sealed class StageConfiguration : DbMigrationsConfiguration<StageDb>
{
public StageConfiguration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = #"Migrations\Stage";
CommandTimeout = 3000;
ContextKey = "FMS.Stage";
}
}
}
And the code that performs the migrations
Database.SetInitializer(new MigrateDatabaseToLatestVersion<StageDb, StageConfiguration>());
var dbMigrator = new DbMigrator(new StageConfiguration());
var logger = new MigratorLoggingDecorator(dbMigrator, new DbMigrationLogger());
foreach (string migration in dbMigrator.GetPendingMigrations())
Console.WriteLine(migration);
logger.Update();
I hope this is clear enough for those willing to try assist. If anyone has a tip, I am all ears. This is making me grey.

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 :)

How to initialize EF Code First Migrations on a remote target

I would like to introduce Code First Migrations to my project, but I am unsure of how to handle deploying this to my client for testing. Until now, things have been quite simple, and I have just used a CreateDatabaseIfNotExists initializer. Now, I have two scenarios:
He deletes his existing, before-migrations, database, and uses an initializer to create a new, with-migrations, database, and we use migrations from here on to upgrade his database. Can I use the MigrateDatabaseToLatestVersion initializer to create the DB if missing as well?
I just deploy my code and let it perform migrations. I'm not quite sure if anything but using a MigrateDatabaseToLatestVersion is required here. Will this upgrade a pre-migrations database to one suitable for migrations?
This is what I do when automatic migration is required; I hope this helps you find a solution:
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<ContextFileName, PathToMigrationsConfig>()
);
Database.Initialize(false);
In the configuration file for the migrations, I set the following in the constructor
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
In the configuration file you should have an override of the seed method, if not you can add it and fill in your seed data.
What the above will do is create/upgrade the database to the latest as long as no data loss occurs. This should allow you hand off the code to the client.
On a side note, for a production system I will usually argue the point of not doing this. This had many disadvantages. For databases I do not have control over I have yet to find a client that has refused the generated script file.
You can get this by using the following command after you add a migration through the Package Manager Console:
Update-database –script -verbose

How to explicitly name the database when using Entity Framework Migrations 4.3

I've recently started using Entity Framework migrations and noticed that the database name is not pulling through for me when I run the Update-Database command.
My connectionstring is:
<connectionStrings>
<add name="DataContext" connectionString="Server=.\SQLEXPRESS;Initial Catalog=TestDB;Trusted_Connection=Yes;" providerName="System.Data.SqlClient" />
</connectionStrings>
The very first time I run Update-Database my database is created with the correct name TestDB. However, as soon as I make a change to one of my entities it will not update any longer for me unless I add a Start Up Project Name (I'm using a multi project solution):
Update-Database -StartUpProjectName "TestDB.Data"
This then makes another new database which migrations will always continue to use. I don't mind having to put in the StartUpProjectName command but is there a way to override the default name for the database this produces? It always creates the database as
TestDB.Data.DataContext
Is there a way to ensure that the database created when passing the StartUpProject name is just called TestDB or is this a limitation of using the StartUpProjectName setting?
As a note, I think the reason I need to specify the StartUpProjectName is that I have a multilayer project setup. The Migrations Configuration file is in my 'Data' project, the entities/models are in my 'Domain' project, etc. I also do not currently have any initialize options in my Global.asax.cs file as I would have used previously on code first ef 4.2. So in my project I just have a DataContext in my Data project and the Migrations Configuration in that project also.
EDIT:
Since I originally setup this question I stumbled onto the 'correct' way to name a database in a multiproject solution. While the answer below will work it does mean you are duplicating your web.config in another area which isn't an ideal solution. Instead you can just put the name into your DbContext by doing something like this (DataContext is just the name I used in my project):
public class DataContext : DbContext
{
public DataContext() : base("DatabaseNameHere")
{ }
public DbSet<Table1> Table1 { get; set; }
public DbSet<Table2> Table2 { get; set; }
public virtual void Commit()
{
base.SaveChanges();
}
}
Thanks,
Rich
You can avoid managing it in app.config by offering it as a parameter:
Update-Database -Verbose
-ConnectionString "CONNECTIONSTRING"
-ConnectionProviderName "System.Data.SqlClient"
-StartupProjectName WEBSITE_PROJECT -ProjectName MIGRATION_PROJECT
Easy-piezy, if you love to type endlessly.
When doing update-database you should specify the project that contains the migrations. Make sure that you have an app.config file in that project that contains the correct connection string.
When splitting up an application over several projects, the connection string used when running the app is the one of the project started. When migrating, the connection string used is the one of the project containing the migrations.
When I did a similar setup I had to add the connection string in two places. A bit awkward, but it works.
You can have your connection string stored in the web.config in your website project and the DBContext and migration files in another project and still share the same connection string. However you need to make sure that as well as setting the Data project (or whatever project has the DBContext etc. in it) as the default project for the Package Manager Console, you ALSO need to make sure that your website is set to the Default StartUp Project!!!
I cannot see this documented anywhere, but a frantic 24 hours of not being able to figure out why my migrations where suddenly being applied to a SQLExpress db, led me to this conclusion.
I tried with Latest EF5 from Nuget.
However Update-Database does not read the App.config from the project that contain the migrations (just like the answer 1 year ago) but it will only read *.config from start up project. It is great but I discover how Add-Migration and Update-Database find a suitable connection string here:
It trying to get "DefaultConnection" connection string first
Then it is trying to get the connection string name based on context class name. E.g. I have the MyContext class derived from DbContext so I can use the "MyContext" connection string name. Useful when I have multiple db connections.
If both the above connection string names are not found, it will fail and show no "DefaultConnection" connection string unless you supply the -ConnectionStringName parameter. See get-help Update-Database to view the help page in the Package Manager Console.
There is no retry or fallback attempt, so if the "DefaultConnection" contains a wrong connection string, it will simply show an error.
If both DefaultConnection and context name exist in the connection strings, DefaultConnection will take precedence.
I would prefer #2 become the first try because the name is more specific but the above steps is what EF5 Migrations do when trying to connect to the db.