[CoreData] Migrating To A New Model With An Extra Entity

As I mentioned in the previous post, I ran into an annoying problem with CoreData very recently:

Problem: We needed to have an evolution of the model, which in its simplest form meant adding an entity.

Naive solution: Well, duh. Lightweight migration will work just fine. If not, just make a mapping model, and you’ll be fine.

Well, no. Every automatic migration ended up into a “Error: table ZRandomNumber_*WhateverRandomEntityFromYourModel* already exists”

After a lot of digging around, annoying any and every contact who remotely knew anything about CoreData, I managed to extract the actual SQL commands it was trying to execute on the SQLite database.

Guess what? it was trying to recreate some of the tables based on relationships (rightly assuming that some of them had changed or had been added, since I added an Entity). But one of them was getting mangled, because it incorrectly assumed none of the relationships preexisted.

Naive solution v2: Well duh, export the database to an agnostic format, then reimport it in the new model.

Yep. That actually works. But I have 140 entities, and close to 300000 rows. After 4h of crunching, I decided to stop the test.

Naive (and I mean REALLY naive) solution that actually works: Find a way to add your new entity at the end of the alphabetical list. That way it creates the missing relationships after having made everything was kosher. I’m not even kidding, I added ZZ in front, and everything just worked. Try it before you loose your own hair.



  1. In my case issue is with table name. I was taking ‘Events’. after i have rename table name with ‘TestEvents’. its solved my issue.

  2. Ciao Zino,
    Same issue here. I have a model that I have been migrating just fine for a couple of years. Latest version was 6.
    Needed to add one simple new entity. Added a new model version 7, and migration when to s**t.
    The new entity has two relationships to existing entities (and, of course, the round-trip relationships in those existing entities back).
    Kept getting the “table exists” error. BTW, the table that was in error had nothing to do with the new one.
    I assumed I had touched the old model accidentally. But no.

    I added “Z” before the name of my new entity, and migration works fine.
    There’s got to be a more-elegant solution.

    Thanks for your insight.

Leave a Reply