Creating initial migration for existing DB results in empty migration - entity-framework

I'm using EF 6.1.2. I have an existing database, and I've Enabled Migrations. When I enter the command AddMigration InitialCreate in the console, the migration that is created is empty. From what I can find researching, that's what should happen if I add the parameter -IgnoreChanges, but I'm not doing that.
Most of the Migrations documentation references EF 4.3. I haven't found anything that says it has changed for 6.1.2. Is there a new command parameter to force the migration to contain the create code? Or is something else missing in my configuration?
Thanks

My application is n-tiered with both a Web API and an MVC project. Because I have multiple start-up projects set, EF was not able to determine which application to use to find the start up configuration. I was applying the Add-Migrations to the Data Access layer but the connection string and entity framework initialization settings were in the MVC web.config. After I copied these to the App.Config of the data access layer, all worked as expected.

Related

Entity Framework Core with split migrations

I am in the process of migrating from EF6 and .Net Framework to EF Core and .Net.
Previously I had a solution for the data model (Data project below) that built and deployed to a nuget package
Solution
Data
SchemaX
...
SchemaY
...
...
Data.Migrations.SqlServer
Migrations
SchemaX
20220701110223_Migration1.cs
...
The data model can then be consumed by any number of separate jobs/apps/etc using the package. This worked fine using EF6. However, if I start again for EF Core I'm seeing the odd issue.
Using the package manager console with default project Data, I can type
add-migration -StartupProject "Data.Migrations.SqlServer" -Context "Data.SchemaXContext" -OutputDir "Migrations\\SchemaX" -Name:CoreInitial
and it will scaffold a migration. The migration ends up in the Data project due to this default. If I use the Data.Migrations.SqlServer as the target/default it cannot find the context - I assume there is something that I could put in this project (other than a reference) to point it in the right direction?
I'm basically trying to migrate frameworks and use the suggestion here to set a start point for core.
NB The Data.Migrations... project is used as the startup as the Data project is .Net Standard 2.0 targetted to allow for use in framework and .Net projects whereas the migrations project has been set to target Framework 4.8.
Edit
Removed the following as it has been fixed by use of the modelBuilder.Ignore<> directive to handle where contexts crossover.
However, what it scaffolds is not limited to the context provided - it basically scaffolds the entire database, all schemas/context items - and using this mechanism as it stands I cannot get it to reference a database for comparison like I could EF6 with it's connection string parameter. I'm not sure whether the scaffolding of the entire model is a configuration issue or the lack of start point database.

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.

No initial create with Entity Framework migrations

I'm trying to get Entity framework migrations working. I've enabled code first migrations, its created a migrations folder, config file and the mig history table, but no initial create. Am i missing a step? This is a new db created by EF (4.3.1).
This behavior is not in place by default, but it is available to you easily in many different forms.
You can call context.Database.CreateIfNotExists(); at application startup.
You can use one of the built-in DatabaseInitializers. The CreateDatabaseIfNotExists initializer is built into EntityFramework and just needs to be added to your project.
You could create your own custom database initializer which includes option #1 inside of itself. Example: Code First Migrations and initialization
You can include DatabaseInitializers in your project either by code or via a config file.
Include an EntityFramework Database Initializer via code:
In your application startup you can setup the DatabaseInitializer like so:
System.Data.Entity.Database.SetInitializer<DairyMmmContext>(new System.Data.Entity.CreateDatabaseIfNotExists<DairyMmmContext>());
NOTE: this code has changed multiple times throughout the life of entityframework! This example is for EF 4.3 which is the current production release available via nuget.
Include an EntityFramework Database Initializer via configuration element:
<configuration>
<entityFramework>
<contexts>
<context type="MyNamespace.MyEFDataContext, AssemblyName">
<databaseInitializer
type="System.Data.Entity.CreateDatabaseIfNotExists`2[[MyNamespace.MyEFDataContext, AssemblyName],
[MyNamespace.Migrations.Configuration, AssemblyName]], EntityFramework" />
</context>
</contexts>
</entityFramework>
</configuration>
You'll notice this can be a little "ungraceful" with this configuration. You need to replace AssemblyName above with the name of the assembly you keep your entityframework stuff in, replace MyNamespace.MyEFDataContext with the fully qualified name of your entityframework data context, and replace MyNamespace.Migrations.Configuration with the fully qualified name to your configuration class (by default in the Migration folder inside your project).
EDIT: Edited to respond to additional comments
A migration is a change from one schema definition to another schema definition. Creating the empty database is not a migration (but everything after that is). There will be no migration source file in your project for just creating an empty db, that is done in code by the initializer.
If you are already using the DropCreateDatabaseAlways initializer it should be doing that. However, I noticed you are setting the initializer in code which means there is the opportunity for a timing problem (setting the initializer after your context is already past the point of calling any initializers).
You can force entityframework to run your initializer at any point in code with context.Database.Initialize(true); (The parameter is a true/false to force the initialization regardless of the current state). That would drop and recreate your database every time.
But you can also just make sure your initializer is setup as early as possible in your application's life cycle (before you have created a single instance of your context).
"Initial Create" is NOT created automatically! You need to create that yourself. Some tutorials of EF are confusing and I had the same misunderstanding as you.
What you need to do:
-Add-Migration InitialModel
If you already have created your database tables and domain model, then:
-Add-Migration InitialModel -IgnoreChanges
From this point, your code will be in sync with database. Anytime you change the code, you can use Add-Migration to add the changes to your database.
The article / tutorial here here (on microsoft.com)
describes the reason that an initialCreate migration doesn't exist. The migration will only be added if the Database already exists. Otherwise, the first migration will be the 'initialCreate' as there is no point in creating a migration to a Database that doesn't exist yet... no DB means there is nothing to roll back to, on a down migration.
Here is the pertinent paragraph:
Run the Enable-Migrations command in Package Manager Console
This command has added a Migrations folder to our project, this new folder contains two files:
The Configuration class. This class allows you to configure how Migrations behaves for your context. For this walkthrough we will just use the default configuration.
Because there is just a single Code First context in your project, Enable-Migrations has automatically filled in the context type this configuration applies to.
An InitialCreate migration. This migration was generated because we already had Code First create a database for us, before we enabled migrations. The code in this scaffolded migration represents the objects that have already been created in the database. In our case that is the Blog table with a BlogId and Name columns. The filename includes a timestamp to help with ordering.
If the database had not already been created this InitialCreate migration would not have been added to the project. Instead, the first time we call Add-Migration the code to create these tables would be scaffolded to a new migration.
Not sure it's the same but I had a similar issue. I think my problem was related to the fact that I dont use a connections string from the config file to get my connection string.
Fiddling with the start up project in the solution and also the projet combo in the Package Manager Console I was able to generate that first migration.
Also make shure you have a connections string with the name of your dbContext class so the Package Manager can find it.
I am using EF 6 RC1 and ran into this problem where neither the InitialCreate nor __MigrationHistory were being created when running Enable-Migrations.
Actually, just after upgrading from EF 5 to EF 6 I ran Enable-Migrations and for some reason it created a __MigrationHistory table using the EF 5 schema, so I deleted it and my Migrations directory and tried to start over.
But every time I deleted the Migrations directory it wouldn't create an InitialCreate or __MigrationHistory. I tried dropping and recreating the database and restarting Visual Studio 2012 to no avail. I gave up for the day and the next morning tried again - after letting my computer sit for about 8 hours it then created the InitialCreate. I am guessing there must be a cache somewhere that has a really long timeout - anyone? I am also guessing that rebooting might clear the cache, but I didn't try that.
Whatever the case, it is possible to use PM> Add-Migration InitialCreate to do that step manually.
Anyway, I still didn't get a __MigrationHistory table. Apparently, EF 6 has changed from creating it during the Enable-Migrations command to instead only creating it during the Update-Database command. And since my schema had already been created at that point, I needed to tear it down and recreate it manually:
PM> Update-Database -TargetMigration:0
PM> Update-Database
I also stopped after the first command to check the state of the database to ensure I was updating the correct one, since according to this, the database connection string is picked up or autogenerated depending on the configuration, and unless it is configured right, there is no guarantee you are going to access the database or instance of SQL Server you intend to.
After running both commands it created a __MigrationHistory table - and it didn't create it as a system table (which I didn't really want anyway), so all is good. Not exactly the same problem as the OP, but hopefully this will be helpful to someone else.
References:
http://elegantcode.com/2012/04/12/entity-framework-migrations-tips/
Reset Entity-Framework Migrations
How to recreate migrations from scratch
I know this is old, but there is no accepted answer and I had same issue.
The trick is Enable-Migrations command. As stated here there is a command Enable-Migrations –EnableAutomaticMigrations. What it does it starts migrations exactly where you are.
If you want the first migration to be creation of database, just run Enable-Migrations (without --EnableAutomaticMigrations).
And remember to set initializer:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<LicenseContext, Configuration>());

add-migration does not function with remote sql server databases in shared hosting

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.