Execute SQL scripts as part of EF code first db initialization

Create a folder for sql scripts and put all *.sql files there. Set the build action of the sql files to EmbeddedResource. Call ExecuteScripts(context) method below from the Seed(context) method of your db initializer.

private void ExecuteScripts(DbContext context)
{
    foreach (var script in GetScripts())
    {
        string sql = GetFromResources(script);
        if (!string.IsNullOrWhiteSpace(sql))
        {
            context.Database.ExecuteSqlCommand(sql);
        }
    }
}

private IEnumerable GetScripts()
{
    return GetType().Assembly
        .GetManifestResourceNames()
        .Where(r => r.EndsWith(".sql"));
}

private string GetFromResources(string resourceName)
{
    using (var stream = GetType().Assembly.GetManifestResourceStream(resourceName))
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s