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.
Last active
November 9, 2021 19:56
-
-
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 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
| /// <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); | |
| } |
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
| public partial class ExampleMigration : Migration | |
| { | |
| protected override void Up(MigrationBuilder migrationBuilder) | |
| { | |
| migrationBuilder.RunSqlScript("your-embed-script"); | |
| } | |
| protected override void Down(MigrationBuilder migrationBuilder) | |
| { | |
| } | |
| } |
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
| 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