我有應用asp.net核心網絡API的應用程序與2個控制器 OracleController.csASP WEB API多個的DbContext
[Route("api/[controller]")]
public class OracleController : Controller
{
private readonly OracleDbContext _db;
public HeatsController(OracleDbContext context)
{
_db = context;
}
...
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
SqlServerController.cs
[Route("api/[controller]")]
public class SqlServerController: Controller
{
private readonly SqlServerDbContext _db;
public HeatsController(SqlServerDbContext context)
{
_db = context;
}
...
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(_ => new OracleDbContext(Configuration["Data:OracleConnectionString"]));
services.AddScoped(_ => new SqlServerDbContext(Configuration["Data:SqlServerConnectionString"]));
}
SqlServerDBContext.cs
public class SqlServerConfig : DbConfiguration
{
public SqlServerConfig()
{
SetProviderServices("System.Data.SqlClient",
System.Data.Entity.SqlServer.SqlProviderServices.Instance);
}
}
[DbConfigurationType(typeof(SqlServerConfig))]
public class SqlServerDbContext : DbContext
{
public SqlServerDbContext()
: base("name=SqlServerDbContext")
{
}
public SqlServerDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
}
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
...
}
}
應用程序啓動後,我只能訪問一個DBContext。例如,如果我從OracleController調用某種方法,它工作正常,但SqlServerController方法不工作,它們會拋出異常「提供的SqlConnection不指定初始目錄或AttachDBFileName。」。如果我首先從SqlServerController調用方法,它的工作方式是相同的。
你有一個基地DbContext你的數據庫上下文?我的意思是一個父母班。 –
兩者都從DbContext繼承; public class OracleDbContext:DbContext {...} – Stopee
好吧,您沒有自定義父類。我認爲你需要檢查你的ConfigureServices方法,我有這個配置Sql Server DbContext:services.AddEntityFrameworkSqlServer()。AddDbContext(); –