asp.netCore连接多个数据库

1.首先要有对应的context实体类,

多个实体类的构造函数的参数都应该是集合

 public class firstContext : DbContext
    {
        //多个数据库应该使用这个构造函数,参数是上下文的集合
        public GalpOnlineContext(DbContextOptions<firstContext> options) : base(options)
        {

        }

        //自定义DbContext实体属性名与数据库表对应名称(默认 表名与属性名对应是 User与Users)
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().ToTable("user");
            modelBuilder.Entity<Project>().ToTable("project");
            //相关表名称的和类的对应
            base.OnModelCreating(modelBuilder);
        }


        public DbSet<User> User { get; set; }
      //....

        //第二种方法,重载父级的构造函数,和配置,这个只能是一个数据库时候的构造函数
        /* 
        public firstContext(DbContextOptions options) : base(options)
        {
            // Using the default constructor
        }*/

    }
}    

 2.在appsettings.json中进行配置数据库连接的信息

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "firstContext": "Server=localhost;database=test;uid=root;pwd=123456;sslmode=none",
    "secondContext": "Server=localhost;database=test2;uid=root;pwd=123456;sslmode=none"
  },

 3.在startup.cs文件中注册数据库上下文的信息

  public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                //  options.CheckConsentNeeded = context => false;实现session,默认是true
                options.CheckConsentNeeded = context => false;  
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //注册数据库的服务
            string connectionString = Configuration.GetConnectionString("firstContext");
            string connectionString2 = Configuration.GetConnectionString("secondContext");

            services.AddDbContext<firstContext>(options => options.UseMySql(connectionString));
            services.AddDbContext<secondContext>(options => options.UseMySql(connectionString2));


            //注册session
            services.AddDistributedMemoryCache();
            services.AddSession(Options =>
          {
              Options.IdleTimeout = TimeSpan.FromSeconds(1000);
              Options.Cookie.HttpOnly = true;
          });
            //services.AddMemoryCache();//使用本地缓存必须添加

            //注册mvc服务
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        }

  然后就可以了,在使用的地方引入上下文就可以了

 public class TestController : Controller
    {
        public readonly firstContext _context;
        //构造函数,依赖注入数据库上下文就可以了
        public TestController(firstContext context)
        {
            _context = context;
        }
        public ActionResult Index(string page)
        {
            List<Project> projects = _context.Project.ToList();
            ViewBag.projects = projects;
            return View();
        }
    }
 

猜你喜欢

转载自www.cnblogs.com/xuqp/p/9707469.html