Reputation: 2545
Is it possible to target multiple database vendors in a single project with Entity Framework? Like: Sql server and DB2.
Right now, I have created 2 DbConfiguration classes:
Sql server:
public class SqlServerEfConfiguration : DbConfiguration
{
public SqlServerEfConfiguration()
{
SetDefaultConnectionFactory(new SqlConnectionFactory());
}
}
DB2:
public class Db2EfConfiguration : DbConfiguration
{
public Db2EfConfiguration()
{
SetDefaultConnectionFactory(new DB2ConnectionFactory());
SetProviderServices("IBM.Data.DB2", DB2ProviderServices.Instance);
}
}
And also 2 dbcontexts:
Sql server:
[DbConfigurationType("TestNewProject.Db.SqlServerEfConfiguration, TestNewProject")]
public class SqlServerDbContext : DbContext
{
public SqlServerDbContext(string conn) : base(conn)
{
}
}
DB2:
[DbConfigurationType("TestNewProject.Db.Db2EfConfiguration, TestNewProject")]
public class Db2DbContext : DbContext
{
public Db2DbContext(string conn) : base(conn)
{
}
}
Then I have my controller:
public class HomeController : Controller
{
private readonly SqlServerDbContext _sqlServerDbContext;
private readonly Db2DbContext _db2DbContext;
public HomeController(Db2DbContext db2DbContext, SqlServerDbContext sqlServerDbContext)
{
_sqlServerDbContext = sqlServerDbContext;
_db2DbContext = db2DbContext;
}
You would expect that the Db2DbContext uses the Db2EfConfiguration, and the SqlServerDbContext uses the SqlServerEfConfiguration. But that's not the case. I am getting an exception when accessing sql server. Accessing DB2 succeeds.
When I remove the Db2DbContext from my constructor, sql server works just fine.
Is there a way to access databases from 2 vendors using Entity Framework 6?
Upvotes: 0
Views: 122
Reputation: 166
Try concrete instantiation and create two different contexts and connection string to these contexts.
public class HomeController : Controller
{
private readonly SqlServerDbContext _sqlServerDbContext = new SqlServerDbContext ();
private readonly Db2DbContext _db2DbContext = new Db2DbContext();
public HomeController()
{
_sqlServerDbContext...
_db2DbContext = db2DbContext...
}
Upvotes: 1