【问题标题】:Asp.net 5 Handling multi-databases structureAsp.net 5 处理多数据库结构
【发布时间】:2021-10-20 20:08:30
【问题描述】:

我正在尝试通过自动迁移来实现多数据库结构。 数据库不可数,我无法设置固定的连接字符串。 我尝试了很多方法来处理它,有些方法有效但无法处理自动迁移。 我有两个不同的 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());
        }

    
    }

【问题讨论】:

  • 这是解决问题的糟糕方法。您是不同的数据库不同的 DbContext 还是相同的 DbContext 但具有不同的连接字符串?
  • @Neil 不同的 DbContext 和不同的连接字符串
  • 连接字符串被添加到启动中的AddDbContext 调用中。如果你知道启动时的连接字符串,为什么还要在控制器中硬编码呢?
  • @PanagiotisKanavos,如何在启动文件中使用动态连接字符串?

标签: asp.net asp.net-core entity-framework-core asp.net5 multi-database


【解决方案1】:

我已使用用户声明来处理此问题


启动

        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();
        }

UserDbContext 类

 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);
        }
        
    }


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多