Teamol
Teamol

Reputation: 819

Passing compile time string to a class

I need to pass const string to a class at compile time. I have a MigrationHistoryRepository class. And I need to have a different schema name for each DbContext that uses it. I was hoping something like this generic aprroach would work but it does not. Is there a way to do this?

public abstract class TextDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        if(!string.IsNullOrWhiteSpace(ConnectionString))
        {
            options.UseSqlServer(ConnectionString);
            options.ReplaceService<IHistoryRepository, MigrationHistoryRepository<"MyTestSchema">>(); // Chaning EF history naming convention
        }
    }
}

public class MigrationHistoryRepository<T> : SqlServerHistoryRepository where T : string
{
    public MigrationHistoryRepository(HistoryRepositoryDependencies dependencies)
        : base(dependencies)
    {
    }

    protected override string TableName { get { return "migration_history"; } }

    protected override string TableSchema => T;

    protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)
    {
        base.ConfigureTable(history);

        history.HasKey(h => h.MigrationId).HasName($"{TableName}_pkey");
        history.Property(h => h.MigrationId).HasColumnName("id");
        history.Property(h => h.ProductVersion).HasColumnName("product_version");
    }
}

!!!!!! EDIT !!!!!!

Edit was moved to a separate question

DependencyInjection cannot find the assebly

Upvotes: 0

Views: 156

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89361

You can't pass strings to generics, only types. But here you have a type to pass.

public class MigrationHistoryRepository<T> : SqlServerHistoryRepository where T : DbContext

and

options.ReplaceService<IHistoryRepository, MigrationHistoryRepository<TextDbContext>>(); 

And then derive the schema name from data availabable from typeof(T), like its name, or a custom attribute you put on it, or a static property or method invoked through reflection.

Upvotes: 1

Related Questions