Created
January 4, 2018 20:47
-
-
Save yzorg/689891a94fc2a49f193d8ba667110b51 to your computer and use it in GitHub Desktop.
Entity Framework Core migration tools: run a .sql script and `DropStoredProcedureIfExists()`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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