Lost data with custom migration CoreData

41 views Asked by At

I'm trying to do a CoreData migration. I need to change the entity relationship from oneToMany to oneToOne in DBEditTextTask

I'm creating a new model and specifying the maxCount = 1 property for NSRelationshipDescription. I'm using NSMigrationManager. Creating my own NSMappingModel and using NSEntityMigrationPolicy

Migration occurs without errors. But the data is lost. My guess is that I am not creating NSMappingModel, NSEntityMapping and NSPropertyMapping correctly. Since when a method is called:

try migrationManager.migrateStore(
                from: storeURL,
                sourceType: NSSQLiteStoreType,
                options: nil,
                with: self.createMappingModel(),
                toDestinationURL: newStoreURL,
                destinationType: NSSQLiteStoreType,
                destinationOptions: nil
            )

the policy methods (createDestinationInstances and createRelationships) is not called

Creating mappingModel:

func createMappingModel() -> NSMappingModel {
        let editableMessageMapping = NSEntityMapping()
        editableMessageMapping.name = "MappingEditTextTask"
        editableMessageMapping.sourceEntityName = "EditTextTask"
        editableMessageMapping.destinationEntityName = "EditTextTask"
        editableMessageMapping.mappingType = .transformEntityMappingType
        editableMessageMapping.entityMigrationPolicyClassName = "TestCoreDataMigration.TaskMigrationPolicy"

        let idPropertyMapping = NSPropertyMapping()
        idPropertyMapping.name = "id"
        idPropertyMapping.valueExpression = NSExpression(format: "$source.id")

        let chatIdPropertyMapping = NSPropertyMapping()
        chatIdPropertyMapping.name = "chatId"
        chatIdPropertyMapping.valueExpression = NSExpression(format: "$source.chatId")

        let relationshipMapping = NSPropertyMapping()
        // add code for mapping

        editableMessageMapping.attributeMappings = [idPropertyMapping, chatIdPropertyMapping]
        editableMessageMapping.relationshipMappings = [relationshipMapping]

        let mappingModel = NSMappingModel()
        mappingModel.entityMappings = [editableMessageMapping]
        return mappingModel
    }

Link to the full version of the project https://github.com/UriyDevyataev/CoreDataMigration

0

There are 0 answers