您可以根据需要实例化任意数量的上下文来分散 SQL 实例并执行伪跨数据库连接、复制数据等。注意,跨上下文连接是在本地执行的,因此您必须调用 ToList()、ToArray() 等来执行查询在加入之前单独使用各自的数据源。换句话说,如果您将来自 DB1.TABLE1 的 10 行与来自 DB2.TABLE2 的 20 行“内部”连接起来,则在 Linq 执行连接并返回相关/相交之前,必须将这两个集合(所有 30 行)都拉入本地计算机的内存中设置(每个示例最多 20 行)。
//EF6 context not selected in Linqpad Connection dropdown
var remoteContext = new YourContext();
remoteContext.Database.Connection.ConnectionString = "Server=[SERVER];Database="
+ "[DATABASE];Trusted_Connection=false;User ID=[SQLAUTHUSERID];Password="
+ "[SQLAUTHPASSWORD];Encrypt=True;";
remoteContext.Database.Connection.Open();
var DB1 = new Repository(remoteContext);
//EF6 connection to remote database
var remote = DB1.GetAll<Table1>()
.Where(x=>x.Id==123)
//note...depending on the default Linqpad connection you may get
//"EntityWrapperWithoutRelationships" results for
//results that include a complex type. you can use a Select() projection
//to specify only simple type columns
.Select(x=>new { x.Col1, x.Col1, etc... })
.Take(1)
.ToList().Dump(); // you must execute query by calling ToList(), ToArray(),
// etc before joining
//Linq-to-SQL default connection selected in Linqpad Connection dropdown
Table2.Where(x=>x.Id = 123)
.ToList() // you must execute query by calling ToList(), ToArray(),
// etc before joining
.Join(remote, a=> a.d, b=> (short?)b.Id, (a,b)=>new{b.Col1, b.Col2, a.Col1})
.Dump();
localContext.Database.Connection.Close();
localContext = null;