Skip to content

Instantly share code, notes, and snippets.

@Eonasdan
Last active November 9, 2021 19:56
Show Gist options
  • Select an option

  • Save Eonasdan/4d6082bf0e6bb7f7597df957d8c538de to your computer and use it in GitHub Desktop.

Select an option

Save Eonasdan/4d6082bf0e6bb7f7597df957d8c538de to your computer and use it in GitHub Desktop.
A EF extension to run SQL scripts as part of a migration

This extension makes it easier to apply script scripts during a migration. Save you scripts to a folder inside our data layer (in the same assembly as the extension) and mark them as embeded.

/// <summary>
/// Added auditable metadata to the entity mapping.
/// </summary>
/// <typeparam name="TProperty"></typeparam>
/// <param name="builder"></param>
public static void AddAuditableMetadata<TProperty>([NotNull] this EntityTypeBuilder<TProperty> builder) where TProperty : class, IAuditableEntity
{
builder.HasOne(t => t.CreatedBy).WithMany().HasForeignKey(t => t.CreatedById);
builder.Property(t => t.CreatedOn).HasColumnName(nameof(AuditableEntity.CreatedOn));
builder.Property(t => t.UpdatedOn).HasColumnName(nameof(AuditableEntity.UpdatedOn));
builder.HasOne(t => t.UpdatedBy).WithMany().HasForeignKey(t => t.UpdatedById);
}
public partial class ExampleMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RunSqlScript("your-embed-script");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
public static void RunSqlScript(this MigrationBuilder migrationBuilder, string script)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = assembly.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith($"{script}.sql"));
using var stream = assembly.GetManifestResourceStream(resourceName);
using var reader = new StreamReader(stream);
var sqlResult = reader.ReadToEnd();
migrationBuilder.Sql(sqlResult);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment