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 comment