【发布时间】:2019-09-20 21:18:51
【问题描述】:
我有一个场景,其中我在 appsettings.json 下定义了多个连接字符串,如下所示:
"ConnectionString": {
"ConnectionZone1": "Server=(localdb)\\mssqllocaldb;Database=Blogging;Trusted_Connection=True;",
"ConnectionZone2": "Server=localhost;Database=Blogging;Trusted_Connection=True;"
},
我也在我的 startup.cs 文件中注册了这个:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DbContextZone1>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ConnectionZone1")));
services.AddDbContext<DbContextZone2>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ConnectionZone2")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
我使用数据库优先方法创建了模型和上下文类,并按如下方式注册了我的上下文类:
public partial class BloggingContext : DbContext
{
public BloggingContext()
{
}
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{
}
public virtual DbSet<Blog> Blog { get; set; }
public virtual DbSet<Post> Post { get; set; }
并创建了另外两个继承自上述主基类的上下文类:
public class DbContextZone1 : BloggingContext
{
public DbContextZone1()
{
}
}
public class DbContextZone2 : BloggingContext
{
public DbContextZone2()
{
}
}
现在我已经创建了我的 API 控制器并尝试调用这些上下文方法。
[HttpGet]
public async Task<ActionResult<IEnumerable<object>>> GetItems()
{
if (alternate)
{
alternate = false;
using (var context = new DbContextZone1())
{
return await context.Blog.ToListAsync();
}
}
using(var context = new DbContextZone2())
{
return await context.Post.ToListAsync();
}
}
问题是当我运行我的应用程序时,它会抛出错误,我的上下文类应该具有参数化构造函数以便传递选项。
那么在 DbContextZone1 和 DbContextZone2 构造函数中会出现哪个上下文选项参数?我试过这样放,但是当我调用 API 控制器时它永远不会工作并抛出错误:
public class DbContextZone1 : BloggingContext
{
public DbContextZone1(DbContextOptions<BloggingContext> options)
: base(options)
{
}
}
public class DbContextZone2 : BloggingContext
{
public DbContextZone2(DbContextOptions<BloggingContext> options)
: base(options)
{
}
}
那么关于如何实现多个连接或使我的代码正确的任何帮助或代码想法或建议?
【问题讨论】:
标签: asp.net-core-webapi ef-core-2.2