如果我理解正确,你有一个SharedServer和一些LocalServers(公司特定),它们想要在单个上下文中拥有两个对象的所有内容(一个是共享的,一个是公司特定的)。
我将给您两种情况:
1. 多对多:在这种情况下,需要关联表的表位于sharedDB中,但是连接它们的第三个表位于公司特定DB中。
2. 单对多:其中一个表位于SharedDB中,另一个表位于公司特定DB中。
Many-to-Many
1. 在SQL侧创建同义词
首先,您必须在本地(或公司特定)数据库中创建同义词:
CREATE SYNONYM [dbo].[StudentCources] FOR [SharedServer].[SharedDB].[dbo].[StudentCources]
假设你的共享表有两列(不要在意)分别叫做 studentID
和 courseID
。
2. 创建 POCOs
假设我们有两个本地数据库上的表,它们之间存在多对多关系。让我们假设第三个连接表(包含键)位于共享数据库中!!(我认为这是最糟糕的方式)。因此,你的 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 中。
一对多
无需任何步骤!只需将 OnModelCreating
修改为:
modelBuilder.Entity(Of Student).ToTable("Students", "dbo")
请注意,在这种情况下,
Students
是一个
同义词。然后创建关系 :)
centraldatabase.dbo.table
,而不是在各个地方创建同义词。或者EF根本不允许跨数据库连接吗? - Aaron Bertrand