DEV Community

JWP
JWP

Posted on

3 1

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)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay