using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations.Operations.Builders; using Oqtane.Migrations.Extensions; namespace Oqtane.Migrations.EntityBuilders { public abstract class BaseEntityBuilder where TEntityBuilder : BaseEntityBuilder { private readonly MigrationBuilder _migrationBuilder; protected BaseEntityBuilder(MigrationBuilder migrationBuilder) { _migrationBuilder = migrationBuilder; ForeignKeys = new List>(); } private void AddKeys(CreateTableBuilder table) { table.AddPrimaryKey(PrimaryKey); foreach (var foreignKey in ForeignKeys) { table.AddForeignKey(foreignKey); } } protected abstract TEntityBuilder BuildTable(ColumnsBuilder table); protected string EntityTableName { get; init; } protected PrimaryKey PrimaryKey { get; init; } protected List> ForeignKeys { get; } public void AddBooleanColumn(string name) { _migrationBuilder.AddColumn(name, EntityTableName); } public void AddDateTimeColumn(string name, bool nullable = false) { _migrationBuilder.AddColumn(name, EntityTableName, nullable: nullable); } /// /// Creates a Migration to add an Index to the Entity (table) /// /// The name of the Index to create /// The name of the column to add to the index /// A flag that determines if the Index should be Unique public virtual void AddIndex(string indexName, string columnName, bool isUnique = false) { _migrationBuilder.CreateIndex( name: indexName, table: EntityTableName, column: columnName, unique: isUnique); } /// /// Creates a Migration to add an Index to the Entity (table) /// /// The name of the Index to create /// The names of the columns to add to the index /// A flag that determines if the Index should be Unique public virtual void AddIndex(string indexName, string[] columnNames, bool isUnique = false) { _migrationBuilder.CreateIndex( name: indexName, table: EntityTableName, columns: columnNames, unique: isUnique); } public void AddStringColumn(string name, int length, bool nullable = false) { _migrationBuilder.AddColumn(name, EntityTableName, maxLength: length, nullable: nullable); } public void AlterStringColumn(string name, int length, bool nullable = false) { _migrationBuilder.AlterColumn(name, EntityTableName, maxLength: length, nullable: nullable); } /// /// Creates a Migration to Create the Entity (table) /// public void Create() { _migrationBuilder.CreateTable(EntityTableName, BuildTable, null, AddKeys); } /// /// Creates a Migration to Drop the Entity (table) /// public void Drop() { _migrationBuilder.DropTable(EntityTableName); } public void DropColumn(string name) { _migrationBuilder.DropColumn(name, EntityTableName); } /// /// Creates a Migration to drop an Index from the Entity (table) /// /// The name of the Index to drop public virtual void DropIndex(string indexName) { _migrationBuilder.DropIndex(indexName, EntityTableName); } } }