Adding new model to existing ones using Code First ef-code-first entity-framework-core visual-studio-2015


Currently I achieve the above as follows.

Question: Is it the right approach in order to keep the data in the exiting tables in tact. I feel I'm doing it rather a long-winded way. Any suggestions or alternate/correct ways of doing it?

  1. Create a new entity (model) and a corresponding DbSet<...> entry in myProjectContext.cs file
  2. Delete existing migration from VS2015 and corresponding __EFMigrationsHistory table from the SQL Server Db
  3. Run PM> add-migration mytMigration -context myProjectContext
  4. Comment out all the code in newly generated mytMigration.cs file except the code related to newly generated entity (model).
  5. Run PM> update-database -context myProjectContext

New table (corresponding to newly added entity) gets created in the exiting Db along with new __EFMigrationsHistory table. Data in all the existing tables remains in tact.


I'm following this official ASP.NET tutorial and - per their advice - have registered our context with dependency injection as follows:


public void ConfigureServices(IServiceCollection services)
            var connection = @"Server=myDevMachine\SQL2012Instance;Database=myDb;Trusted_Connection=True;";
            services.AddDbContext<ABCTestContext>(options => options.UseSqlServer(connection));
1/9/2017 3:22:17 PM

Popular Answer

You should not delete anything existing. You are adding right?

Steps you should be doing:

  1. Create new entity
  2. Add DbSet to context
  3. Run add-migration newMigrationName
  4. Run update-database

Add-Migration looks at the existing database and model and generates a migration to update the schema.

When you run Update-Database, EF checks the migration history table and runs the migrations that were not yet executed.

1/12/2017 8:43:27 AM

Related Questions


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