DEV Community 👩‍💻👨‍💻

John Peters
John Peters

Posted on

EF (code first) Migration and Update to database

EF Code First in Visual Studio

If you are using EF Code first, you already know about DBSETs and Entity Models. Adding or removing fields, changing namespaces, and altering property types in any Entity Model is common during the development cycle.

But how do you get these changes out to the database with a clean set of data?

Get a clean build first and then...

Add a Migration for the New Schema

Add-Migration XYZMigrationName 
  -Project XYZProjectName.Data
  -StartupProject XYZProjectName.Web.Api 
  -Context DBStore
Enter fullscreen mode Exit fullscreen mode

Drop the Existing Database in SSMS

USE [master]
GO
alter database [DBName] set single_user with rollback immediate
DROP DATABASE [DBName]
GO
Enter fullscreen mode Exit fullscreen mode

Udpate the Database

Update-Database 
  -Project XYZProjectNsme.Data 
  -StartupProject XYZProjectName.Web.Api 
  -Context DBStore
Enter fullscreen mode Exit fullscreen mode

The database should be completely new with proper changes and data (if you use seed data)...

Note that the Add-Migration and Update-DataBase commands can be run from PackageManager Console window within Visual Studio. Or Powershell, or Visual Studio code Termial Window...

JWP2020

Top comments (0)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠