Creating entity instance in doctrine migrations - symfony

I'm having this problem:
In a symfony2 application using Doctrine, during the first dev milestone, I created a migration to update the database schema. The migration I created was container-aware in order to be able to create standard entries in the entity manager (a Config entity instance) in the postUp method. This worked very well until today, when I created a new migration that adds fields in the config entity.
When I run doctrine:migrations:migrate here is what happens:
The first migration runs it's up() method, tables are created according to milstone#1 mapping info
The first migration's postUp() method is called, and it uses the entity manager to try creating a new config instance. But since at this point the second migration was not run, persisting the instance fails because database schema is not in sync with entity mapping info.
Is there any way to work-around this problem ?

Related

How to add a new column to an existing entity with typeorm

I am starting to study typeorm and I am confused about what happens if I add a new column to an existing entity that was already persisted with data. I use SQlite.
I saw in the documentation, in the "Migrations" section, it looks like there is a procedure that must be done if I want to add a new column.
But when I saw this issue in typeorm's github, I understood that if I just add the new "#Column" annotated property to the Entity class would be enough and typeorm would create the column automatically when the app starts.
I was really hoping that typeorm would be able to handle that schema change automatically.
Can someone help?
TypeOrm is capable of changing the schema but is does not run migrations automatically on server start (this is not a wanted behaviour). If you want the migrations to be executed when the app the starts you need to todo the following to steps:
Create migration file:
After changing your entity (like adding a new column) you need to generate a migration file:
typeorm migration:generate -c 'connectionName'
That migration file is then created into a folder configured in your ormconfig.json.
Run migrations
Before you start your server, you need to create the database connection and run the migrations. So your main file should look like
import { Connection, getConnectionManager } from 'typeorm';
const connectionManager = getConnectionManager();
const connection = connectionManager.get(connectionName);
await connection.runMigrations();
// start your server
startServer();
For development purpose you can also use schema synchronization, in that case typeorm syncs your database with your entity:
npx typeorm schema:sync -c 'connectionName'

.Net Core Entity Framework core, using new database for each test in same test class

I have a few tests to test the patching functionality. I am using this custom factory
https://github.com/aspnet/Docs/blob/master/aspnetcore/test/integration-tests/samples/2.x/IntegrationTestsSample/tests/RazorPagesProject.Tests/CustomWebApplicationFactory.cs
For each test, I want to create new database or at-least clear and seed data again. Because other tests are messing up with data.
You can use
db.Database.EnsureDeleted();
This ensures that the database for the context does not exist. If it does not exist, no action is taken. If it does exist then the database is deleted.

override database with new Migrations asp.net core

I created a new migration for my asp.net core Web API which applied the changes to my database, But I later deleted the migration manually. I now tried to add a new migration with new changes and but it is giving the error bellow since the changes from the migration I deleted were applied to the database already.
An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: There is already an object named 'FK_TaskDates_Tasks_TaskId' in the database.
Could not create constraint or index. See previous errors
Long story short, I'm trying to return the database state back to what it was before the deleted migration was applied.
Is there a way for me to revert the database back to it's working state?
Migrations work by comparing the new migration to the last one run. If there are no prior migrations, it will script out everything in the database.
Generally, for existing database with no prior migrations, you will need to add baseline migration. With EF6 you can use the -IgnoreChanges flag for this baseline. EF Core does not have that (unless recently added), so you can work around it by commenting out the stuff already in the database in the Up() method and applying it. The important thing is that a copy of the model is captured for future comparisons.
Now the next migration you add will only include the changes from that model stored in the code file.
To get your current system working, just comment out the stuff that already exists in the Up() method and keep the changed stuff and apply it (update-database).

MigrateDatabaseToLatestVersion seed() doesn't create tables in database [duplicate]

In my application I enable Code First Migrations with some migrations, Also I use SQL Server Compact for integration test.
When I run my tests, Entity Framework create an empty database and tries to run migration on that empty database and thrown The specified table does not exist.
Based on this report I think usage of Migration in Entity Framework 6 has changed.
I test all Database Initializer with Context.Database.Create(); but in all case tabale's never created.
I don't know that this is EntityFramework's bug or not, but when I made rename the namespace of Migration Configuration class from default (Projectname/Migrations) to any none default name, migration works well.
Context.Database.Create() will not execute migrations! It only creates empty db. To Update database from code to latest version you need to use DbMigrator.Update method:
var migrator = new DbMigrator(new MyMigrationsConfiguration());
migrator.Update();
Alternatively you might use MigrateDatabaseToLatestVersion
Database.SetInitializer(new MigrateDatabaseToLatestVersion<BlogContext, Configuration>());
It is described in details here: http://msdn.microsoft.com/en-us/data/jj591621.aspx#initializer
In case someone still struggles to fix the issue.
The code that follows works for me: add-migration MyFirstMigration
Meanwhile add-migration "MyFirstMigration" with the migration name ramped in quote doesn't work.
There may be previous migration files which the ide may be referring to mostly likely due to caching.
Drop backup and drop target database if it exists, and drop the migration folder.
Now add the migration and you will be good to go.
It does happens when adding model and running add-migration command.
Here is the simplest cause of this issue:
Add a newly added model property into IdentityDbContex class.
Here are the steps:
create model
add property into IdentityDbContex class
run add-migration
update-database

Can you create a database without migrations in EF5?

I am following the offical asp.net "Getting started with EF 5 using MVC 4". In that tutorial, the database is created when the migrations are performed(in my understanding). When I was looking at the EF 5 with Mvc 5 tutorial they didn't use migrations to create a database. They use database initializer. So, I was wondering could create a database for your project without using migrations in EF 5? Also, what would the difference be with both these approaches?
Code first Migrations and using Package Manager Console Commands to do upgrades can get a bit confusing at first.
You can use the initializer to CreateDatabaseIfNotExists , DropCreateIfModelChanges, DropCreateDatabaseAlways and to MigrateDatabaseToLatestVersion
See the interface IDatabaseInitializer<TContext>.
CreateDatabaseIfNotExists // is the Default initializer.
So this is why it appears EF just does things for you sometimes.
So the answer is "YES you can "Create a Database without Migrations"
But the difference is not obvious and if you would do that long term is another question.
If you are using migrations. It would Update the Db to match the code first model.
If there is NO database, then that means creating the database.
So Thats why Automated migrations and CreateDB look confusing since they can result in same outcome sometimes. But technically they are different.
So generally it is sufficient to use code first automatic "migrations" only.
Migrations can be either Automatic or "managed".
The managed migrations approach invovles generating code , tweaking the code and running PM commandlet or POwershell command to actually perform the migration.
With Automated migrations you just need set the intitializer and Access the DBContext.
There are 2 parts to the process.
a) The DB Initializer step.
do this immediately before instantiating YourDBContext.
//eg
// DONT TOUCH MY DB or i break your back!
Database.SetInitializer(new ContextInitializerNone<YourDbContext>()); // Do Nothing,
// OR
// yes migrate my db to match my code please.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<YourDbContext, YourMigrationConfiguration>()); // Set to migration is requested, see config class below
The Confirguration class specified when using Migration initializer looks like this
public class YourMigrationConfiguration<TContext> : DbMigrationsConfiguration<TContext>
where TContext : DbContext{
protected YourMigrationConfiguration() {
AutomaticMigrationsEnabled = true; // run it when needed. Do not wait for my PM Command
AutomaticMigrationDataLossAllowed = true; // if the new db look means dropping tables or columns go ahead and kill my data. So use this option with caution.
}
then just trigger the migration in code when required.
Context.Database.Initialize(true); // i place this inside a method on my UoW class
Code first Db initialization strategies.
Code first migrations recommended reading
Managed Migrations
There are many articles on the web on this topic.

Resources