1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

EntityFramework 6で接続文字列から規定のスキーマ名を設定する

Posted at

DbModelBuilderクラスのHasDefaultSchemaメソッドにスキーマ名を指定することで、TableAttributeでSchemaを指定しない場合の規定のスキーマを設定できますが、環境ごとにスキーマを分けたいときに困るので、接続文字列から規定のスキーマ名を設定するようにしました。

DbContextを継承したクラスで、HasDefaultSchemaメソッドに接続文字列から取得したUSER IDの値を与えます。
スキーマ名は、大文字でないとOracleにテーブルが無いと怒られるため、ToUpperメソッドで大文字にしています。

Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
    Dim schema = ""
    If ParseConnectionString(Me.Database.Connection.ConnectionString).TryGetValue("USER ID", schema) Then
        modelBuilder.HasDefaultSchema(schema.ToUpper())
    End If
End Sub

Private Shared Function ParseConnectionString(connectionString As String) As IDictionary(Of String, String)
    Return connectionString.Split(";"c).
        Select(Function(item As String) item.Split("="c)).
        ToDictionary(
            Function(itemArray) itemArray.First.ToUpper(),
            Function(itemArray) itemArray.ElementAtOrDefault(1)
        )
End Function
1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?