Skip to content

Instantly share code, notes, and snippets.

@yzorg
Created January 4, 2018 20:47
Show Gist options
  • Save yzorg/689891a94fc2a49f193d8ba667110b51 to your computer and use it in GitHub Desktop.
Save yzorg/689891a94fc2a49f193d8ba667110b51 to your computer and use it in GitHub Desktop.
Entity Framework Core migration tools: run a .sql script and `DropStoredProcedureIfExists()`
using System;
using System.IO;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Yzorg.EFCore.Migrations
{
internal static class MigrationBuilderExtensions
{
/// <summary>
/// Only works for `dbo` schema.
/// </summary>
public static MigrationBuilder DropStoredProcedureIfExists(this MigrationBuilder builder, string storedProcedureName)
{
builder.Sql(
$@"IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND OBJECT_ID = OBJECT_ID('dbo.{storedProcedureName}'))
DROP PROCEDURE [dbo].[{storedProcedureName}]
GO");
return builder;
}
public static MigrationBuilder RunFile(this MigrationBuilder builder, string filename)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
string data = AppDomain.CurrentDomain.GetData("DataDirectory") as string ?? AppContext.BaseDirectory;
string sqlPath = null;
sqlPath = Path.Combine(data, "sql", filename);
if (File.Exists(sqlPath))
{
builder.Sql(File.ReadAllText(sqlPath));
}
else
{
// TODO: I usually replace this generic exception with `AppMigrationException`.
throw new Exception($"Migration .sql file not found: ${filename}");
}
return builder;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment