当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - ASP WEB API multiple DBContext

问题描述:

I have app asp.net core web api app with 2 controllers

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)

{

...

}

}

After app starts I can access only one DBContext. For example if I call some method from OracleController it works fine but methods from SqlServerController dont work they throw exception " The supplied SqlConnection does not specify an initial catalog or AttachDBFileName.". It works in the same way if i call methods from SqlServerController first.

网友答案:

As you can see in the error message you are missing InitialCatalog property in your connection string. This is required to specify to which database EntityFramework should connect and launch queries against.

分享给朋友:
您可能感兴趣的文章:
随机阅读: