1

I have an existing Code First model created using Entity Framework. Tables are already created and SQL Express and have records in most of the tables.

Now I wanted to add a new table using Code First approach.

The problem is that I haven't found any simple solution to make this addition automatic. I tried the following:

  1. Using Update-Database -ConnectionStringName
    • does not work as this wants to remove all the tables first, even if my update was just an addition of a new table
  2. Adding to MyContext constructor the following line:

    Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());

    • again, does not work as this does not expect any table to be present in a database. Frankly speaking why is it called "migration" when it cannot cater for migrating existing data? It should be called "Creation"?

The only way it works is a manual workaround to backup all the existing data to CSV, remove the entire database and then using BULK INSERT to put the data back. However this is lenghtly manual operation that I would like to avoid.

Is it possible that EF6 still does not handle such a basic model change automatically?

Radek Strugalski
  • 560
  • 7
  • 22
  • possible duplicate of [How to add new table to existing database code first](http://stackoverflow.com/questions/23662755/how-to-add-new-table-to-existing-database-code-first) – Ajay Jan 22 '15 at 11:53
  • I checked the above one, however my question is about addting a table and **preserving** the data of tables that were aready created. – Radek Strugalski Jan 23 '15 at 09:40

1 Answers1

0

If your database created by entity framework it has a table named "__MigrationHistory". Entity framework creates/uses the table to save migration history of your database. You can add a configuration for your DbContext:

public class Configuration : DbMigrationsConfiguration<YourDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
         }

        protected override void Seed(YourDbContext context)
        {
           base.Seed(context);

        }
    }

And in your application starting place (in winForms applications program.cs-> main class) you should write:

System.Data.Entity.Database.SetInitializer(new 
System.Data.Entity.MigrateDatabaseToLatestVersion<YourDbContext, 
YourNameSpace.Configuration>());
isaeid
  • 543
  • 5
  • 26
  • This is what I already tried. See my answer's list point 2. I am looking for a solution that preserves data in tables that wheren't changed. – Radek Strugalski Jan 23 '15 at 09:37