dynamically change the connection of a dbcontext

-1

I need to change the connection (Server and / or database) when creating a new DBContext instance of EF6.0 I'm working with VB.Net from Visual Studio 2017 Does anyone know how to do it? Thank you so much regards Francisco

    
asked by Francisco 22.06.2017 в 23:44
source

1 answer

0
  

First of all notice that I'm a C # programmer, I put a little bit of   code in VB, I hope it's okay.

If you use CodeFirst, you just pass the connection string to the base class of the DbContext constructor.

Partial Public Class Entities
    Inherits DbContext
    Public Sub New(ByVal constring As String)
        MyBase.New(constring)
    End Sub

If you use EFDesigner you must modify the T4 Context.tt template to implement a constructor that passes the connection string to the DbContext

I think that in VB the second constructor to add to the template T4 should be more or less like this:

        Public Sub New(ByVal constring As String)
        MyBase.New(constring)
<#
If Not loader.IsLazyLoadingEnabled(container) Then
#>
        MyBase.Configuration.LazyLoadingEnabled = False
<#
End If

For Each entitySet As EntitySet In container.BaseEntitySets.OfType(Of EntitySet)()
    ''' Note: the DbSet members are defined below such that the getter and
    ''' setter always have the same accessibility as the DbSet definition
    If Not Accessibility.ForReadOnlyProperty(entitySet) = "Public"
#>
        <#=codeStringGenerator.DbSetInitializer(entitySet)#>
<#
    End If
Next
#>
    End Sub

and as a result I should give you two constructors:

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


Public Sub New(ByVal constring As String)
    MyBase.New(constring)
End Sub

in the second constructor you must pass the connection string.

Greetings,

    
answered by 23.06.2017 в 00:05