When executing Entity Framework 5 migrate the executable does several things;
- Check current migrations vs the build
- Execute all migrations that aren't already executed on the target database
- Execute the seed method
This seed method is what we'll focus on. You can access the method by overriding the seed method of the DbMigrationsConfiguration of your project.
Seed will be executed regardless of the state of the target database. This could be useful to run checks, log, send mails... Be careful however to use the seed method to alter the database (which is tempting considering you get the context model). Migrations and Seed each run in a different transaction. This means trouble if one of them fails and doesn't roll back the other. If you want to alter the database you should do so by adding code int the Up and Down method of the corresponding migration.
Code Snippet
- Protected Overrides Sub Seed(context As PocModel)
- MyBase.Seed(context)
- End Sub
Sorry for the vb.net
Code Snippet
- Imports System
- Imports System.Data.Entity.Migrations
- Namespace Schema
- Partial Public Class Migration_42
- Inherits DbMigration
- Public Overrides Sub Up()
- 'Here
- Sql("ALTER TABLE dbo.MeaningOfLife DROP COLUMN Famine")
- End Sub
- Public Overrides Sub Down()
- 'And here
- End Sub
- End Class
- End Namespace
Sorry for the vb.net
Take into account that executing sql like this is against the spirit of Entity Framework. All table alterations should be done by editing the domain and migrating the database. Unfortunately we don't always have the luxury to adhere to this philosophy. Sometimes legacy columns need to be addressed or we might really need that stored procedure. To accommodate this you'll find a helper class below which reads embedded sql files and splits them into single commands which you can then execute as shown above. Code is provided as-is without express or implied warranty of any kind.
Code Snippet
- Imports System.IO
- Imports System.Text
- Imports System.Data.Entity.Migrations
- Public Class SQLScriptHelper
- Public Function GetCommandsFromEmbeddedFile(uri As String) As List(Of String)
- Return ReadCommandsFromEmbeddedFile(uri)
- End Function
- Public Function ReadCommandsFromEmbeddedFile(uri As String) As List(Of String)
- Dim commands = New List(Of String)
- Dim command = New StringBuilder()
- Dim line As String = "/****** Initial ******/"
- Using stream As IO.Stream = Me.GetType().Assembly.GetManifestResourceStream("YourResourceNamespace." + uri)
- Using reader As StreamReader = New StreamReader(stream)
- While Not reader.EndOfStream
- line = reader.ReadLine()
- If line.Equals("GO") Then
- commands.Add(command.ToString())
- command.Clear()
- Else
- command.AppendLine(line)
- End If
- End While
- End Using
- End Using
- Return commands
- End Function
- End Class
Sorry for the vb.net
Geen opmerkingen:
Een reactie posten