Home > Software engineering >  How to change connection string IDesignTimeDbContextFactory in run time
How to change connection string IDesignTimeDbContextFactory in run time

Time:09-15

I want to be able to change the connectionstring of IDesignTimeDbContextFactory in run time.

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<erp_colombiaDbContext>
{
    public erp_colombiaDbContext CreateDbContext(string[] args) 
    {
        var options = new DbContextOptionsBuilder<erp_colombiaDbContext>().UseMySql(
                @"SECRECT CONNECTION STRING SHOULD BE PARAMETER",
                optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(DesignTimeDbContextFactory).Assembly.FullName))
            .Options;

        return new erp_colombiaDbContext(options);
    }

When I am generating the data here I have some tables that should be in a diffrent database

public class erp_colombiaDbContext : IdentityDbContext<Employee, Entities.Type, ulong>
{

    public erp_colombiaDbContext(DbContextOptions options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        //For exemple the family should be in database 2
        builder.Entity<Family>().HasIndex(t => t.FamilyName).IsUnique(); 
        //And the news author should be in database 1
        builder.Entity<NewsAuthor>().HasKey(t => new { t.NewsId, t.EmployeeId });
    }
}

CodePudding user response:

add connection string in appsettings.json file

{
  "ConnectionStrings": {
    "DefaultConnection": "<your server name>Catalog=GeeksStore;
        Integrated Security=True;Connect Timeout=30;Encrypt=False;
        TrustServerCertificate=False;ApplicationIntent=ReadWrite;
        MultiSubnetFailover=False"
  }  
}

and in create context method

public class DesignTimeDbContextFactory : 
        IDesignTimeDbContextFactory<StoreContext>
   {
        public StoreContext CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
            var builder = new DbContextOptionsBuilder<StoreContext>();
            var connectionString = configuration.GetConnectionString("DefaultConnection");
            builder.UseSqlServer(connectionString);
            return new StoreContext(builder.Options);
        }
    }

for more step-by-step details - https://geeksarray.com/blog/entity-framework-core-code-first-migration-using-separate-assembly

CodePudding user response:

you can update your OnModelCreating method and use Fluent API to configure schema for each table

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<model name1>().ToTable("my sql table name1", "schema name1");
    modelBuilder.Entity<model name2>().ToTable("my sql table name2", "schema name2");       
}
  • Related