Entity Framework Core migrations: how to handle them properly in teams - entity-framework-core

I got into an argument with a co-worker regarding EF Core migrations and how we should handle them in a team environment. The current process we use (which I designed) is to use a migration number as the migration name and request that every migration has a different number.
The goal of that rule is to make sure that all migration are applied in the order they are designed. If two devs work on different migrations at the same time in their own branch and use the same number, the last one to merge his code into master will have remove his migration and re-add it with a new number.
My co-worker argues that this add unnecessary work since most of the time migrations because to one another are fully independent: they will work on different aspects of the schema and therefore it doesn't matter in which order they are finally applied.
My answer to that is that this is an unacceptable risk: if two PRs creates incompatible migrations, it is next to impossible to fix the problem without reverting both PR and redo the work.
(I am aware that the current process isn't perfect: it is still possible to insert two migrations with the same number if the PRs that contains them are accepted independently or in the incorrect order. I don't have a good solution for that)
And am I overly cautious with this? Are there any best practices regarding this?

Related

Entity Framework migration falsly detected as pending

I merged 2 migrations that were previously applied on the database into one
Now the dbContext correctly detects, that the model is compatible using context.Database.CompatibleWithModel
Problem starts after a new migration was added. The model is now not compatible, so the migrator will apply pending migrations. The problem is, that the merged migration is also detected as pending.
Any ideas, what could be the problem here?
OK, not the cleanest solution, but this is the least painful path I found
Rename the last partial migration in database to the name of the merged migration and delete the other partial migrations
This needs to be done before the update process, which is a pity, but the number of instalations is not that high, so it's doable.
Alternative approach would be to run a script that does it before the migrations are applied, but I don't like to have one-time obscure hacks as part of the project

Entity Framework code first - development strategies

Working on a brand new project from the ground up. That means the data model is in a constant flux, doubly so because things are, inevitably, not as well planned as they should be. Model classes are being created and changed fairly regularly.
The plan was to use the latest version of EF with all the neat code-first stuff in it. But we're constantly tripping over the limitations the framework has in terms of adding or updating tables. The initialization options seem to allow only the complete deletion and re-creation of the database, which isn't really ideal.
I've had a look at the migrations. But this seems a sledgehammer to crack a nut: we don't need to detail every single small change and update with a new migration scaffold.
Are there some better strategies to deal with this? For instance, I started writing some unit tests to pre-populate one of the contexts with some test data, but because this causes the whole Db to drop and re-create, it causes problems with all the other contexts. Or perhaps making use of a custom initialiser to seed the data for us? How can we easily exclude these in production code?
We're also wondering about perhaps abandoning code-first and going back to EDMX diagrams. At least that way changes result in updated SQL commands which can be run directly against the database.
Any suggestions gratefully received.
I think, imho, that:
as the database schema must at least match your model you should/must detail every single change, and code first migration allows that and trace the changes over time
code first migration also allows to migrate the database schema for you
code first migration also allows you to produce sql that allows you to migrate the schema
For these reasons code first is as good (if not better) as the edmx approach
Please take few minutes to implement http://msdn.microsoft.com/en-us/data/jj591621.aspx
One other point, always imho and in a perfect world, if you unit test the business of you model you should not need the DAL, use generic collection. Be aware of different comportement of linq to object vs linq to entities, for example concerning the case sensitivity.

Can I fix Entity Framework Code First Migrations?

Background:
I'm developing an application with Entity Framework Code First and have been using my POCO Model to describe the database schema as much as I can. However there are a few cases where only the migrations API supports what you want (such as adding an index). I didn't want to start adding migrations until later, it's much faster just to recreate the database at this point, however it seemed like the only option.
So I thought I'd see if I could see if migrations would work. I planned on using them eventually and I was hoping I'd just be able to adjust the Initial migration or regenerate it as I went, until it was time to make real migrations. However I had no real luck with this approach either. It seems like code migrations for entity framework are fundamentally flawed in that they force the schema to be stored (serialized) as part of the migration.
For me it meant that there was no possible way to adjust the migration as I had no way to update the Target property (which is essentially a serialized version of my model). I also can't regenerate the migration because there is no way to express the indices separately. Part of the problem is that the way migrations work forces them to be made in a serial fashion, which is terrible when I want to update past migrations or there are multiple developers.
I've therefore chosen to just use context.Database.ExecuteSqlCommand to add the indices however I want to figure out if this limitation in migrations is going to change in the future or if I can work around it.
Question:
Is there any way to update the IMigrationMetadata for an existing migration and is there a way to have a migration that doesn't need the metadata found in the Target field?

Automatic migrations or code based migrations ? Which is better choice?

I am trying to decide code first migration strategies but not sure that which is better one.
I actualy liked automatic migrations but not sure that it can create more headache.
I have read this article and he is advocating code-based migrations. But i will not need to switch to different state in migrations so i will always use latest one and i am working in the project as single developer.
Suggestions ?
Automatic migrations were initially also referred as "with-magic migrations" whereas code-based migrations were referred as "no-magic migrations". These two names reflect exactly what is going on. Automatic migrations are implicit - you simply don't care and let them run as they need to. Code-based migrations are explicit - you define migrations in predefined steps and EF guides you in this (for example by not allowing more than one pending migration).
If you just want to have your database always up to date and you don't expect to support multiple versions or downgrades you should be OK with automatic migrations.

DevExpress XPO vs NHibernate vs Entity Framework: database upgrading issue

What is the best practice for upgrading the database using ORM (DevExpress XPO, NHibernate or MS Entity Framework)?
I'm starting a new project and have to pick an ORM. The development process requires of releasing intermediate test builds quite often and likely that each build will have changes in the database structure. Each new version has to upgrade the DB gently to keep current data.
For old solutions I would provide a set of SQL scripts for upgrading the database from v1 to v2, from v2 to v3, etc. and execute them sequentially.
But how is it going to work for ORM? Should I still write SQL scripts to upgrade the DB?
I understand that simple adding new fields wouldn't cause a problem (e.g. see UpdateSchema() method for XPO), but what if I have to split a table and reallocate current records into 2 new tables?
I can't comment on the other ORM's, but I have used DevExpress XPO for a corporate treasury application since 2007. The schema changes a little with every release but there have also been some big schema changes over the years as well. A somewhat extended version of the default XPO upgrade mechanism has comfortably catered for all the changes.
There is good basic information here about upgrading XPO applications.
DevExpress provide a DBUpdater tool to assist you with the task of upgrading production environments. You can extend this tool to cater for additional requirements. In my application, we have added some options for logging, preview with rollback, etc.
Each module has virtual UpdateDatabaseBeforeSchemaUpdate() and UpdateDatabaseAfterSchemaUpdate() methods. You can significantly control the upgrade process within these.
As you mention, some of the upgrade will be handled automatically by XPO (e.g., adding a new column), but some things need additional control such as initialising the new column with a default value for existing records.
For instance, let's say MyNewField has been added to the MyEntity XPO class in version 2.0 of your application. Let's say it should default to a value of 3 for existing records. XPO will handle the creation of the new column but existing records will be NULL. (If you specify a default value in the XPO class it would only pertain to new records). In order to correct the value for existing records you would add something like the following to entity module's overridden UpdateDatabaseAfterSchemaUpdate():
public override void UpdateDatabaseAfterUpdateSchema()
{
base.UpdateDatabaseAfterUpdateSchema();
if (CurrentDBVersion < new Version(2, 0, 0, 0))
ObjectSpace.GetSession().ExecuteNonQuery(
"UPDATE [MyEntity] SET [MyNewField] = 3 WHERE [MyNewField] IS NULL");
}
(You could also use ObjectSpace.GetObjects<MyEntity>() and a foreach if you prefer to avoid the direct SQL.)
In your more extreme example of splitting a table in two, you can use the same method, but you would override UpdateDatabaseBeforeUpdateSchema() instead, run the SQL to split the table, let XPO perform any other schema updates and, if necessary, populate any default values in the UpdateDatabaseAfterUpdateSchema().
You will find that you bump into constraint problems e.g., foreign key violations so you might find you need to write some general routines such as DropAllForeignKeyConstraints() as part of the UpdateDatabaseBeforeUpdateSchema(). Sometimes you find that XPO already provide something, sometimes not. Missing constraints and indexes will get regenerated in the schema update. (In my experience switching a master data table's primary key turned out to be the hardest update routine to get right.)
By default the calls all happen in an SQL transaction so if anything fails it should all roll back.
The developers need to be aware of when a change to the domain model is likely to cause a problem with the underlying schema.
For testing, we keep a few old customer databases and run a bunch of before-and-after tests as part of the build process to make sure that existing customers are able to upgrade properly whatever version they are upgrading from. In production whenever we run into a problem upgrading, the problem data is added into this test library to prevent similar problems in the future.
We are dealing with major international companies and banks. The customers are quite happy with the result. In situations where a corporate's DBA needs to sign off on the changes, they don't seem to mind having a command line tool to do the upgrade rather than a script.
Most migration solutions can handle easy tasks, like adding new column, relationship or removing one, but fail to work when you rename a column (is that an add? or a remove following an add which equals a rename? What should you do with the data in that case?)
All three solutions have basic migrations support, XPO even lets you run your own scripts as a part of the process (to insert static/test/contant data, etc.)
There's also the MigratorDotNet project that you can use and not to rely on any ORM specific feature regarding migrations.
Personally, I would use auto migration only in dev/test environment and would have full set of upgrade scripts when running on client specific database to say upgrade from v1 to v2.
How is it going to work for ORM? Should I still write SQL scripts to
upgrade the DB?
Clear answer of this question should be on Programmer's stackexchange thread - What are the criteria for evaluating an ORM for.NET?, there i got simple answer for your question that you asked and matches with my experience with ORM while developing some project with Entity framework and Code smith ORM templates.
How does the ORM manages changes in the data model? what if I have to split a table and reallocate current records into 2 new tables?
Some can update the DB automatically within a certain measure, other
don't do anything and you'll have to do the dirty work yourself; other
provide a framework for handling change that lets you control database
updates. That means every couple of days someone needs to spend an hour updating the model to add a table or change datatypes that are changing
Ref:
https://softwareengineering.stackexchange.com/questions/6543/what-are-the-benefits-of-using-database-abstraction-by-orm
https://softwareengineering.stackexchange.com/questions/41739/best-arguments-for-against-introducing-orm-technology-into-a-companies-dev-proce/41833#41833
If you ask - what is the best practice for upgrading the db using ORM - my answer is: Don't use it if your application is more than a hobbyist app.
There are a lot of scenarios where many ORMs are unable to provide support to your specific database needs, e.g. in creating stored procedures, create indices and views or even indexed views/materialized tables without writing sql scripts. Problems like adding a new non-nullable column to an existing table are much harder to solve in ORM-Migration-Code than by writing SQL scripts.
Current Tools like Visual Studio Data Tools do handle these kind of problems way better.