在ConfigureServices方法中添加DbContext服务的连接字符串后,是否可以更改它?

时间:2019-05-13 12:12:23

标签: c# asp.net-core asp.net-core-mvc ef-core-2.2

我的appsettings.json中有2个连接字符串,我使用dbContext.Database.Migrate();如果我在ConfigureServices方法中用于创建DbContext服务的主要连接字符串不正确,则在Configure方法中创建数据库的方法将导致Exception,因此我想在异常区域中更改Dbcontext服务的连接字符串。 我该如何实现?

我试图在ConfigureServices中进行迁移,但是我不知道如何创建DbContext对象以及如何对其进行测试。

在ConfigureServices

        services.AddDbContext<RedContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

在“配置”中

        using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var dbContext = serviceScope.ServiceProvider.GetService<RedContext>();
            var roleManager = serviceScope.ServiceProvider.GetService<RoleManager<IdentityRole>>();
            var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
            // Create the Db if it doesn't exist and applies any pending migration.
            try
            {
                dbContext.Database.Migrate();// throws exception if CS is wrong
                DbSeeder.Seed(dbContext, roleManager, userManager);
            }
            catch (Exception)
            {                   
                // remove old service and create new dbcontext DI service in IserviceCollection with secondary connection string
                //dbContext.Database.Migrate();
                // dbContext.Database.GetDbConnection()
            }

2 个答案:

答案 0 :(得分:0)

YourDBContextClass dbcontext = new YourDBContextClass("alternateconnectionstringname");

尝试一下。

P.S在您的DbContext中添加一个辅助变量,以执行以下操作:

 public partial class YourDBContextClass
 {
    // Add a constructor to allow the connection string name to be changed
 public YourDBContextClass(string connectionStringNameInConfig)
        : base("name=" + connectionStringNameInConfig)
    {
    }
}

答案 1 :(得分:0)

我认为这会起作用。

为您的上下文创建新的构造函数

public partial class RedContext
 {
    // Add a constructor to allow the connection string name to be changed
 public RedContext(string connectionStringNameInConfig)
        : base("name=" + connectionStringNameInConfig)
    {
    }
}

更改配置:

 using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var dbContext = serviceScope.ServiceProvider.GetService<RedContext("alternateconnectionstringname")>();
            var roleManager = serviceScope.ServiceProvider.GetService<RoleManager<IdentityRole>>();
            var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
            // Create the Db if it doesn't exist and applies any pending migration.
            try
            {
                dbContext.Database.Migrate();// throws exception if CS is wrong
                DbSeeder.Seed(dbContext, roleManager, userManager);
            }
            catch (Exception ex)
            {                   
            }
}