Asp.net 5处理多数据库结构



我正在尝试实现多数据库结构与自动迁移。数据库数不清,我不能设置一个固定的连接字符串。我尝试了许多方法来处理它,有些方法有效,但无法处理自动迁移。我有两个不同的dbcontext和不同的连接字符串问题是:这是一个好办法还是有更好的办法?

public class CategoriesController : Controller
{
private readonly UserDbContext _context;
public CategoriesController(UserDbContext context, ApplicationDbContext _Maincontext)
{
var conn = _Maincontext.Users.FirstOrDefault().DbId;
context.Database.SetConnectionString($"Data Source=.\SQLEXPRESS;Initial Catalog={conn};Integrated Security=False; uid=sa;password=123;");
context.Database.Migrate();
_context = context;
}
// GET: Categories
public async Task<IActionResult> Index()
{
return Ok(await _context.Categories.ToListAsync());
}

}

我使用了Users Claims处理这个问题

启动

public void ConfigureServices(IServiceCollection services)
{
// First Context which has a static connection string
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("mainDb")));
// To inject HttpContext for each request
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Second Context which has a dynamic connection strings
services.AddDbContext<UserDbContext>();
).AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
}
<<p>UserDbContext类/strong>
public class UserDbContext : DbContext
{
private readonly HttpContext _httpContext;
public UserDbContext(DbContextOptions<UserDbContext> options, IHttpContextAccessor httpContextAccessor = null)
: base(options)
{
_httpContext = httpContextAccessor?.HttpContext;
}
//..
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
//First get user claims    
var claims = _httpContext?.User.Claims.ToList();
//Filter specific claim    
string dbName = claims?.FirstOrDefault(x => x.Type.Equals("db", StringComparison.OrdinalIgnoreCase))?.Value;

if (dbName == null) dbName = "TempDebugDb";
optionsBuilder.UseSqlServer(GetConnectionString(dbName));

}
}
private static string GetConnectionString(string dbName)
{
return $"Data Source=.\SQLEXPRESS;Initial Catalog={dbName};Integrated Security=False; uid=sa;password=*****;";
}

public DbSet<Category> Categories { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}

}

相关内容

  • 没有找到相关文章

最新更新