发布:2023/12/7 15:38:08作者:大数据 来源:大数据 浏览次数:456
.net core多数据库连接与注册:
When registering multiple DbContext types make sure that the constructor for each context type has a DbContextOptions<TContext> parameter rather than a non-generic DbContextOptions parameter.”
意思是在DbContext各自的构造函数中指名options的类型,如下两个dbcontext
1 2 3 |
public EventDbContext(DbContextOptions<EventDbContext> options) : base(options) { } |
1 2 3 |
public MyDbContext( DbContextOptions<MyDbContext> options) : base(options) { } |
在start文件中添加数据库连接
1 2 |
services.AddDbContext<MyDbContext>(options => options.UseMySql(Configuration.GetConnectionString(nameof(MyDbContext)))); services.AddDbContext<EventDbContext>(options => options.UseMySql(Configuration.GetConnectionString(nameof(EventDbContext)))); |
利用IOC实现多数据连接如下:
System.InvalidOperationException
HResult=0x80131509
Message=The DbContextOptions passed to the StudentDbContext constructor must be a DbContextOptions<StudentDbContext>. When registering multiple DbContext types make sure that the constructor for each context type has a DbContextOptions<TContext> parameter rather than a non-generic DbContextOptions parameter.
Source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.DbContext..ctor(DbContextOptions options)
at IocDemoWebApp.Models.StudentDbContext..ctor(DbContextOptions options, IConfiguration configuration) in D:\Source\Repos\IocDemoWebApp\IocDemoWebApp\Models\StudentDbContext.cs:line 14
startup.cs
1 2 |
services.AddDbContext<StudentDbContext>(); services.AddDbContext<MyDbContext>(); |
以上说明是当注册多个dbcontext里,需要在dbcontext的构造函数里加上对应的DbContextOptions<TContext>
1 2 3 4 |
public StudentDbContext(DbContextOptions<StudentDbContext> options, IConfiguration configuration) : base(options) { this.configuration = configuration; } |
1 2 3 4 |
public StudentDbContext(DbContextOptions<MyDbContext> options, IConfiguration configuration) : base(options) { this.configuration = configuration; } |
© Copyright 2014 - 2025 柏港建站平台 ejk5.com. 渝ICP备16000791号-4