私が正しく理解していれば、SharedServerといくつかのLocalServer(会社固有)があり、両方のすべてのオブジェクト(1つは共有、もう1つは会社固有)を単一のコンテキストに入れたいと考えています。
2つのシナリオを紹介します。
- 多対多:この場合、関係を持つテーブルはsharedDBにありますが、それらを結合する3番目のテーブルは会社固有のDBにあります。
- 単一対多:テーブルの1つはSharedDBにあり、もう1つは会社固有のDBにあります。
多対多
1.SQL側でシノニムを作成する
まず、ローカル(または会社固有)のDBにシノニムを作成する必要があります。
CREATE SYNONYM [dbo].[StudentCources] FOR [SharedServer].[SharedDB].[dbo].[StudentCources]
共有テーブルにとという名前の2つの列(関係ありません)があるstudentID
としcourseID
ます。
2.POCOを作成します
ローカルDBに、相互に多対多の関係にある2つのテーブルがあるとします。そして、3番目のジョイナーテーブル(キーを含む)が共有DBにあるとしましょう!! (私はそれが最悪の方法だと思います)。したがって、POCOは次のようになります。
Public Class Student
Public Property studentID as Integer
Public Property Name as String
Public Property Courses as ICollection(Of Course)
End Class
と
Public Class Course
Public Property courseID as Integer
Public Property Name as String
Public Property Students as ICollection(Of Student)
End Class
および共有のもの:
Public Class StudentCources
Public Property courseID as Integer
Public Property studentID as Integer
End Class
コンテキストは次のようになります。
Partial Public Class LocalContext
Inherits DbContext
Public Sub New()
MyBase.New("name=LocalContext")
End Sub
Public Overridable Property Students As DbSet(Of Student)
Public Overridable Property Courses As DbSet(Of Course)
Protected Overrides Sub OnModelCreating(ByVal modelBuilder As DbModelBuilder)
modelBuilder.Entity(Of Student).HasMany(Function(e) e.Courses).WithMany(Function(e) e.Students).Map(Sub(e)
e.MapLeftKey("studentID")
e.MapRightKey("courseID")
e.ToTable("StudentCources", "dbo")
End Sub)
End Sub
End Class
のコードはOnModelCreating
、リレーションテーブルが(直接ではなく)同義語であることをモデルビルダーに通知します。同義語がSharedDBにあることがわかります。
1対多
ステップはありません!次のように変更するだけOnModelCreating
です。
modelBuilder.Entity(Of Student).ToTable("Students", "dbo")
Students
この場合は同義語であることに注意してください。次に、関係を作成します:)