Skip to content

Instantly share code, notes, and snippets.

@samalone
Created December 26, 2017 19:45
Show Gist options
  • Save samalone/da33a527357b5e8ef51db9591a6f7cd7 to your computer and use it in GitHub Desktop.
Save samalone/da33a527357b5e8ef51db9591a6f7cd7 to your computer and use it in GitHub Desktop.
Drop, create, and seed an EntityFramework database for unit testing
Imports System.Data.Entity
Imports System.Data.Entity.Migrations
Public Class DropCreateAndSeed(Of TContext As DbContext, TMigrationConfiguration As {DbMigrationsConfiguration(Of TContext), New})
Implements IDatabaseInitializer(Of TContext)
Public Sub InitializeDatabase(context As TContext) Implements IDatabaseInitializer(Of TContext).InitializeDatabase
Dim step1 = New DropCreateDatabaseAlways(Of TContext)()
step1.InitializeDatabase(context)
Dim step2 = New MigrateDatabaseToLatestVersion(Of TContext, TMigrationConfiguration)()
step2.InitializeDatabase(context)
End Sub
End Class
@samalone
Copy link
Author

When writing unit tests for an EntityFramework application, it's helpful to reset the database to a known state at the start of the unit tests. Entity framework has a DropCreateDatabaseAlways class that resets the database, but it doesn't call the Migration.Configuration.Seed() function. It also has a MigrateDatabaseToLatestVersion class that calls the Seed function, but it doesn't reset the database. This class does both.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment