我有2个控制器的app asp.net core web api app OracleController.cs
[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调用方法,它的工作方式相同。
答案 0 :(得分:0)
正如您在错误消息中看到的那样,您的连接字符串中缺少InitialCatalog
属性。这需要指定EntityFramework应连接到哪个数据库并启动查询。