实体连接字符串通过ini文件

时间:2014-04-09 14:22:05

标签: vb.net entity-framework

如何存储实体框架的连接字符串并从ini文件中调用它。我能够使用ado和vb.net轻松实现这一点,但是实体连接字符串分配不同我想要存储在ini文件中的是服务器用户名和密码。在远离应用程序代码的安全文件夹中。

这就是我在app app中连接的内容

<add name="DeliveryEntities" connectionString="metadata=res://*/Delivery.csdl|res://*/Delivery.ssdl|res://*Delivery.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=DAVID-PC\SQLEXPRESS;initial catalog=Delivery;user id=sa;password=;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

出于原因发出的密码

1 个答案:

答案 0 :(得分:1)

首先,将当前连接字符串更改为不包含用户名和密码。

然后,更改您的DeliveryContainer以接受其中DbConnection的构造函数:

Public Partial Class DeliveryContainer
    Inherits DbContext

    Public Sub New(conn As DbConnection)
        MyBase.New(conn, True)
    End Sub

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

    '....
End Class

现在,您必须使用存储在INI文件中的信息构建自己的EntityConnection

Public Shared Function GetConnection() As EntityConnection
    Dim dbServerName = iniConf("dbServerName")
    Dim dbDatabaseName = iniConf("dbDatabaseName")
    Dim dbUserId = iniConf("DbUserId")
    Dim dbUserPassword = iniConf("DbUserPassword")

    Dim configCs = ConfigurationManager.ConnectionStrings("DeliveryEntities").ConnectionString
    Dim entityCsBuilder = New EntityConnectionStringBuilder(configCs)

    Dim sqlCsBuilder = New SqlConnectionStringBuilder(entityCsBuilder.ProviderConnectionString)

    ' Inject your username and password from the INI file (if exists)
    If dbUserId IsNot Nothing AndAlso dbUserPassword IsNot Nothing Then
        sqlCsBuilder.UserID = dbUserId
        sqlCsBuilder.Password = dbUserPassword
    End If

    sqlCsBuilder.DataSource = dbServerName
    sqlCsBuilder.InitialCatalog = dbDatabaseName

    entityCsBuilder.ProviderConnectionString = sqlCsBuilder.ConnectionString

    Return New EntityConnection(entityCsBuilder.ConnectionString)
End Function

创建新DeliveryContainer时:

Dim context = New DeliveryContainer(GetConnection())