ADO.NET Entity Data Model(edmx)で生成した接続文字列をコードで生成する。
ADO.NET Entity Data Model(edmx)で生成した場合
app.config内部にmetadataを含むConnectionStringが生成される。せっかく自動生成したEntity Data Modelを再利用しながら、ConnectionStringをConfigファイルから隠したいため、コードベースで生成する必要があった
DataContext修正
edmxの内部のDbContextクラスにDbConnectionをもらうコンストラクタを追加する。
Partial Public Class DbEntities Inherits DbContext Public Sub New() MyBase.New("name=DbEntities") End Sub ' 追加 Public Sub New(conn As DbConnection) MyBase.New(conn, True) End Sub End Class
追記:DALの更新時、追加したコンストラクタが消えてしまう事がわかったため、別のAppDbContextクラスで対応
Public Class AppDbContext Inherits DbContext Public Sub New(conn As Common.DbConnection) MyBase.New(conn, True) End Sub ''' ''' 以下の部分はDbEntitiesの自動生成プロパティをコピー・ペーストしてあげる。 ''' End Class
DBコネクション処理修正
' Initialize the connection string builder Dim sqlBuilder As New SqlConnectionStringBuilder() With { .DataSource = "localhost", .InitialCatalog = "testdb", .UserID = "sa", .Password = "mypassword", .IntegratedSecurity = True } ' Initialize the EntityConnectionStringBuilder. Dim entityBuilder As New EntityConnectionStringBuilder() With { .Provider = "System.Data.SqlClient", .ProviderConnectionString = sqlBuilder.ToString(), .Metadata = "res://*/DbModel.csdl|res://*/DbModel.ssdl|res://*/DbModel.msl" } _dbContext = New DAL.AppDbContext(New EntityConnection(entityBuilder.ToString()))