Fix foreign key design error while migrating

.net-core c# entity-framework-core

Question

I have the following situation, my design looks like this and the database already has some data in it.

public class MyContext : DbContext
{
    public DbSet<MyEntity> MyEntities { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=database.db");
    }
}

public class MyEntity
{
    public int MyEntityId { get; set; }

    public int MetaEntityId { get; set; }

    public MetaEntity MetaEntity { get; set; }
}

public class MetaEntity
{
    public int MetaEntityId { get; set; }
}

I later realized, that this was my mistake and the design actually should have been:

public class MyContext : DbContext
{
    public DbSet<MyEntity> MyEntities { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=database.db");
    }
}

public class MyEntity
{
    public int MyEntityId { get; set; }

    public MetaEntity MetaEntity { get; set; }
}

public class MetaEntity
{
    public int MetaEntityId { get; set; }

    public int MyEntityId { get; set; }

    public MyEntity MyEntity { get; set; }
}

What is the best way to apply this migration without losing the relations between the entities? Is there any way inside the Migrations Up() Method to remember the relations, change DB schema and then reapply the relations?

1
0
2/10/2019 11:15:21 AM

Popular Answer

Ok so I found the solution (does not work in SQLite!, code above was just a sample, actual production database is MySQL).

In the new migration move this to correct place after creating the new column and before dropping the old one:

migrationBuilder.Sql("UPDATE MetaEntity " +
                             "INNER JOIN MyEntity ON MetaEntity.MetaEntityId = MyEntity.MetaEntityId " +
                             "SET MetaEntity.MyEntityId = MyEntity.MyEntityId;");
0
2/10/2019 3:15:04 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow