Entity framework working with multiple connection strings vb.net

954 views Asked by At

I am using entity framework and have multiple databases to work with. I would like different users to connect to different databases. In my connection string in web.config, it goes like this.

 <add name="ADBEntities" connectionString="metadata=res://EF_DAL;provider=Oracle.ManagedDataAccess.Client;provider connection string=&quot;data source=pc:15/xe;password=l;user id=l&quot;" providerName="System.Data.EntityClient" />
 <add name="BDBEntities" connectionString="metadata=res://EF_DAL;provider=Oracle.ManagedDataAccess.Client;provider connection string=&quot;data source=pc:15/xe;password=2;user id=2&quot;" providerName="System.Data.EntityClient" />

In my auto generated file from model1.context.vb, the following is generated

Partial Public Class DBEntities
    Inherits DbContext

    Public Sub New()
        MyBase.New("name=DBEntities")
    End Sub

what i would like to do is to be able to have the users connect to different database. I figured out being a partial class. I tried to create another class like this

Partial Public Class DALEntities
    Inherits DBEntities

    Private Sub New(nameOfConnectionString As String)
        MyBase.New(nameOfConnectionString)
    End Sub
End Class

However of course it will not work becos DBEntities does not have a New() which takes in arguments. Is there a way to overcome this by editing settings in the autogeneration process or to overcome this problem programatically.

2

There are 2 answers

0
Jason Richmeier On BEST ANSWER

You could simply create a class that inherits directly from DbContext instead of the auto-generated class.

This assumes that the database schemas referenced by each connection string are the same. If they are not, there would be a bit more work to do as far as the model is concerned.

0
Lionel Koh On

Seems that declaring this method in a seperate class did the trick for me

Partial Public Class DBEntities

Private Sub New(nameOfConnectionString As String)
    MyBase.New(nameOfConnectionString)
End Sub

End Class