How to setup Elsa with custom schema and table creation without entity framework

438 Views Asked by At
  • Need to change Schema for Elsa tables
  • Need to avoid DDL operation for Elsa hosting service so I want to create all required tables before starting Elsa

I tried to override ElsaContext, but I do not have a clear idea of the implementation. I tried the following:

public class SqlElsaContextFactory : IDesignTimeDbContextFactory<ElsaContext>
{
    
    public ElsaContext CreateDbContext(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddCommandLine(args)
            .Build();

        var dbContextBuilder = new DbContextOptionsBuilder();
        var connectionString = configuration.GetConnectionString("Elsa");

        dbContextBuilder.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(typeof(Program).Assembly.FullName));

        return new ElsaContextExtension(dbContextBuilder.Options);
    }
}

public class ElsaContextExtension : ElsaContext
{
    public ElsaContextExtension(DbContextOptions options) : base(options)
    {
    }

    protected string _schema = "test";
    public override string Schema => _schema;
}

But getting the below error:

Table creation error

1

There are 1 best solutions below

2
On

You can inherit from ElsaContext and override what you need. Something like this:

public class WorkflowDbContext : ElsaContext, IDbContext
{
    public bool ProxyCreationEnabled { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    public bool AutoDetectChangesEnabled { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

    public WorkflowDbContext(string connectionString) : base(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options)
    {

    }
}

Then you can generate the SQL scripts like this:

private string CreateDatabaseScript()
{
    return this.Database.GetService<IRelationalDatabaseCreator>().GenerateCreateScript();
}

Then install the scripts like this:

public void Install()
{
    var scriptsBatch = this.CreateDatabaseScript();
    foreach (var script in scriptsBatch.Split("GO", StringSplitOptions.RemoveEmptyEntries))
    {

        this.Database.ExecuteSqlRaw(script);
     }
}

So by calling this Install method you can generate the tables before starting Elsa.